聽起來像您想要使用自定義排序順序進行排序。可以想到兩種方法:1)將排序順序放入表中並在查詢中使用該表; 2)使用分隔字符串(假設域中值的數量很小,穩定,值相似和「窄」的寬度)。
請原諒SQL Server語法,但相當標準,希望你得到的總體思路:
例如1
WITH MyTable (ID, data_col)
AS
(
SELECT ID, data_col
FROM (
VALUES (1, 'aa'),
(2, '111'),
(3, 'ccc'),
(4, 'bbb'),
(5, '111'),
(6, 'aa'),
(7, '111'),
(8, 'bbb')
) AS MyTable (ID, data_col)
),
MyDomainWithSortOrder (domain_col, sort_seq)
AS
(
SELECT ID, domain_col
FROM (
VALUES ('bbb', 1),
('111', 2),
('aa', 3),
('ccc', 4)
) AS MyDomainWithSortOrder (ID, domain_col)
)
SELECT T1.ID, T1.data_col, D1.sort_seq
FROM MyTable AS T1
INNER JOIN MyDomainWithSortOrder AS D1
ON T1.data_col = D1.domain_col
ORDER
BY sort_seq;
例如, 2
WITH MyTable (ID, data_col)
AS
(
SELECT ID, data_col
FROM (
VALUES (1, 'aa'),
(2, '111'),
(3, 'ccc'),
(4, 'bbb'),
(5, '111'),
(6, 'aa'),
(7, '111'),
(8, 'bbb')
) AS MyTable (ID, data_col)
)
SELECT ID, data_col
FROM MyTable
ORDER
BY CHARINDEX(CAST(data_col + ' ' AS CHAR(3)), 'bbb111aa ccc');
最擅長http://stackoverflow.com/questions/1793147/sql-best-practice-to-deal-with-default-sort-order/1793162#1793162 – 2010-07-20 12:03:25