繁体   English   中英

如何在SQL Server 2005中执行自定义排序

[英]How to do Custom Sorting in SQL Server 2005

我想按CustomercodetblCustomer表进行自定义排序。

CustomerCode(3 char of Surname) + 1 + (PostCode)

如果找到相同的姓氏和邮政编码客户,则此处将增加1。

对于例如ABB12615ABB22615

所以主要我想按此排序

First 3 Letters of Surname + Index + PostCode.

我试图以这种方式做:

ORDER BY CHARINDEX(SUBSTRING(customerCode, 1, 3), customerCode)

但是它给了我这样的输出:

ABB12615
ABB12715
...
...
...
..
.
ABB22615

但我想按以下顺序输出:

 ABB12615 

 ABB22615

 ABB12715 

等等

有可能吗?

根据您的预期结果,您确实要进行排序

Surname, postcode, index

那将是

ORDER BY SUBSTRING(customerCode, 1, 3), 
         SUBSTRING(customerCode, 5, 4), 
         SUBSTRING(customerCode, 4, 1)

尝试这个

SELECT * 
FROM TABLE1
ORDER BY CASE WHEN COlumn1 = 'ABB12615' THEN 1
              WHEN COlumn1 = 'ABB22615' THEN 2
              WHEN COlumn1 = 'ABB12715' THEN 3
              END

此代码应按所需方式排序。

-- 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)

测试运行的输出。

在此处输入图片说明

是的,它有可能。 假设您的CustomerCode格式保持不变,则可以使用以下代码。 您需要基于字符串函数&拆分客户代码,然后再对索引进行排序,需要将它们转换为整数,如下所示:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM