[英]How to do Custom Sorting in SQL Server 2005
我想按Customercode
對tblCustomer
表進行自定義排序。
CustomerCode
由(3 char of Surname) + 1 + (PostCode)
如果找到相同的姓氏和郵政編碼客戶,則此處將增加1。
對於例如ABB12615
, ABB22615
所以主要我想按此排序
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.