Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在SQL Server 2012中自定义此数据的排序?_Sql_Sql Server_Sorting - Fatal编程技术网

如何在SQL Server 2012中自定义此数据的排序?

如何在SQL Server 2012中自定义此数据的排序?,sql,sql-server,sorting,Sql,Sql Server,Sorting,我很难弄清楚如何按照我想要的方式对数据进行自定义排序。这意味着它应该按如下顺序排列: 201-1-1 201-1-2 201-1-3 ....... 201-2-1 等等,如果你明白我的意思 取而代之的是,我将执行以下代码: select * from test.dbo.accounts order by account_name asc 输出: 201-10-1 201-10-2 201-1-1 201-11-1 201-11-2 201-11-3 201-11-4 201-11-6

我很难弄清楚如何按照我想要的方式对数据进行自定义排序。这意味着它应该按如下顺序排列:

201-1-1
201-1-2
201-1-3
.......
201-2-1
等等,如果你明白我的意思

取而代之的是,我将执行以下代码:

select * 
from test.dbo.accounts 
order by account_name asc
输出:

201-10-1
201-10-2
201-1-1
201-11-1
201-11-2
201-11-3
201-11-4
201-11-6
201-1-2
201-12-1
201-12-2
201-12-3
201-12-4
201-12-6
201-1-3
201-13-1
201-13-2
201-13-3
201-13-4
201-13-6
201-1-4
201-14-1
201-14-2
201-14-4
201-14-6
201-15-1
201-15-2
201-15-3
201-15-4
201-15-6
201-1-6
201-16-1
201-16-2
201-16-3
201-16-4
201-16-6
201-16-7
201-1-7
201-17-1
201-17-2
201-17-4
201-17-6
201-18-1
201-18-2
201-18-3
201-18-4
201-18-6
201-19-1

谢谢你。SQL中的字符串操作可能非常麻烦。也许有更好的方法可以做到这一点,但这似乎确实有效

select accoutn_name
from test.dbo.accounts
order by left(account_name,charindex('-',account_name,1)-1)
                        ,replace(right(left(account_name,CHARINDEX('-',account_name,1)+2),2),'-', '')
                        ,REPLACE(right(account_name,2),'-','')
顺便说一句,这是一个非常昂贵的过程运行。如果它是生产化的,你会想提出一个更好的解决方案


啊。SQL中的字符串操作可能非常麻烦。也许有更好的方法可以做到这一点,但这似乎确实有效

select accoutn_name
from test.dbo.accounts
order by left(account_name,charindex('-',account_name,1)-1)
                        ,replace(right(left(account_name,CHARINDEX('-',account_name,1)+2),2),'-', '')
                        ,REPLACE(right(account_name,2),'-','')
顺便说一句,这是一个非常昂贵的过程运行。如果它是生产化的,你会想提出一个更好的解决方案


对于示例数据,以下技巧将起作用:

order by len(account_name), account_name
这仅仅是因为唯一的可变长度组件是第二个组件,并且因为连字符比数字“小”


您应该规范化帐户名称,以便所有组件的长度相同,方法是将数字左填充为零。

对于示例数据,以下技巧将起作用:

order by len(account_name), account_name
这仅仅是因为唯一的可变长度组件是第二个组件,并且因为连字符比数字“小”


您应该规范化帐户名称,以便所有组件都具有相同的长度,方法是用零填充数字。

对不起,实际上您的解决方案是正确的。一开始我没有注意到另一个没有正确分组。谢谢教授,实际上你的解决方案是正确的。一开始我没有注意到另一个没有正确分组。谢谢