[英]How to do Custom Sorting in SQL Server 2005
I want to do custom sort by Customercode
for tblCustomer
table. 我想按
Customercode
对tblCustomer
表进行自定义排序。
CustomerCode
consist of (3 char of Surname) + 1 + (PostCode)
CustomerCode
由(3 char of Surname) + 1 + (PostCode)
Here, 1 will increment if Same Surname and postcode customer found. 如果找到相同的姓氏和邮政编码客户,则此处将增加1。
For eg ABB12615
, ABB22615
对于例如
ABB12615
, ABB22615
So mainly I want to sort this by 所以主要我想按此排序
First 3 Letters of Surname + Index + PostCode.
I tried to do in this manner : 我试图以这种方式做:
ORDER BY CHARINDEX(SUBSTRING(customerCode, 1, 3), customerCode)
but it gives me output like this: 但是它给了我这样的输出:
ABB12615
ABB12715
...
...
...
..
.
ABB22615
But I want output in this order: 但我想按以下顺序输出:
ABB12615
ABB22615
ABB12715
and so on 等等
Is it possible to do? 有可能吗?
Based on your expected results you really want to sort on 根据您的预期结果,您确实要进行排序
Surname, postcode, index
which would be 那将是
ORDER BY SUBSTRING(customerCode, 1, 3),
SUBSTRING(customerCode, 5, 4),
SUBSTRING(customerCode, 4, 1)
Try this 尝试这个
SELECT *
FROM TABLE1
ORDER BY CASE WHEN COlumn1 = 'ABB12615' THEN 1
WHEN COlumn1 = 'ABB22615' THEN 2
WHEN COlumn1 = 'ABB12715' THEN 3
END
This code should sort the way you want. 此代码应按所需方式排序。
-- play table
create table #postal
(
id int identity(1,1) primary key,
code varchar(16)
)
go
-- remove data
truncate table #postal;
go
-- add data
insert into #postal
values
('ABB12615'),
('ABB22615'),
('ABB12715'),
('AAA29615'),
('AAA19615');
go
-- sort
select
*
from
#postal
order by
substring(code, 1, 3),
substring(code, 5, len(code) - 5),
substring(code, 4, 1)
Output from the test run. 测试运行的输出。
Yes its possible. 是的,它有可能。 Assuming that your CustomerCode format will remain the same, you can use the below code.
假设您的CustomerCode格式保持不变,则可以使用以下代码。 You need to split the Customercode based on String functions & before sorting index, need to convert them to integer as shown below:
您需要基于字符串函数&拆分客户代码,然后再对索引进行排序,需要将它们转换为整数,如下所示:
select * from tblCustomer
ORDER BY
SUBSTRING(Customercode , 1, 3) --SurName
,CONVERT(INT, SUBSTRING(Customercode , 4, 1)) --Index
,CONVERT(INT,SUBSTRING(Customercode , 5, 5)) --Post Code; You can optionally remove the convert to int function if your post code will contain characters
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.