排序键值的SQL查询

时间:2018-02-28 11:12:42

标签: sql sorting

如何在sql中为每列排序数据?

例如C1列的第一行中的值为“CAB”,并且您希望输出中的值为“ABC”

输入

C1
CAB
ZSA

输出

C1
ABC
ASZ

1 个答案:

答案 0 :(得分:1)

您可以尝试这种逻辑,也许有更好的解决方案,但它可以完成工作

DECLARE @t TABLE (Id INT, C1 VARCHAR(255))
INSERT INTO @t VALUES (1, 'CAB'),(2, 'ZSA')

;WITH mcte AS (
    SELECT split.Id, split.C1, split.c, ASCII(split.c) AS asciinr
    FROM (
        SELECT a.Id, a.C1, SUBSTRING(a.C1, v.number+1, 1) AS c
        FROM @t AS a
            join master..spt_values v on v.number < LEN(a.C1)
        WHERE v.type = 'P'
    ) AS split
) 

SELECT  Id, c1, REPLACE(STUFF((SELECT ' ' + mcte2.c FROM mcte AS mcte2 
                               WHERE mcte2.C1 = mcte.C1 and mcte2.Id = mcte.Id 
                               ORDER BY mcte2.asciinr FOR XML PATH('') ), 1, 1, ''), ' ', '') as OrderedC1

FROM    mcte
GROUP BY Id, c1
ORDER BY mcte.C1

<强>结果

Id  C1   OrderderC1
-------------------
1   CAB  ABC
2   ZSA  ASZ