如何按字母顺序排序字符串

时间:2014-12-30 05:45:49

标签: sql-server sql-server-2008 sorting

我有一张包含以下数据的表

Item
......
xzypq
abdcfe

如何对列中的字符串进行排序并获得以下结果?

Item
......
pqxyz
abcdef

2 个答案:

答案 0 :(得分:2)

可以尝试以下链接,这可能有助于http://social.technet.microsoft.com/wiki/contents/articles/19492.sort-letters-in-a-phrase-using-t-sql.aspx

/*Create sample table*/
IF OBJECT_ID('tempdb..#Text', 'U') IS NOT NULL
DROP TABLE #Test;

CREATE TABLE #Test
(
  ID INT IDENTITY(1, 1) ,
  Phrase VARCHAR(255)
);

/*Populate the table with sample data*/
INSERT  #Test
    ( Phrase )
VALUES 
( 'CHICAGO' ),
( 'NEW YORK' ),
( 'HOUSTON' ),
( 'SAN FRANCISCO' );



/*This is the final solution*/;
WITH    base
      AS ( SELECT   L.[char] ,
                    T.ID ,
                    T.Phrase
           FROM     #Test T
                    CROSS APPLY ( SELECT    SUBSTRING(T.Phrase, 1 + Number, 1) [char]
                                  FROM      master..spt_values
                                  WHERE     Number < DATALENGTH(T.Phrase)
                                            AND type = 'P'
                                ) L
         )
SELECT  DISTINCT
        b1.Phrase ,
        REPLACE(( SELECT    '' + [char]
                  FROM      base b2
                  WHERE     b1.Phrase = b2.Phrase
                  ORDER BY  [char]
                    FOR
                      XML PATH('')
                ), '&#x20;', ' ') AS columns2
FROM    base AS b1;

答案 1 :(得分:0)

使用Recursive CTE也可以这样做。

SELECT 'xzypq' NAME
INTO   #temp
UNION ALL
SELECT 'abdcfe' 

递归CTE

;WITH cte
     AS (SELECT Cast(NAME AS VARCHAR(50)) AS st,NAME AS name1,1 AS rn
         FROM   #temp
         UNION ALL
         SELECT Cast(Substring(NAME, rn, 1) AS VARCHAR(50)),name1,rn + 1
         FROM   cte a
                JOIN #temp b
                  ON a.name1 = b.NAME
                     AND rn < Len(a.name1) + 1)
SELECT DISTINCT (SELECT '' + st
                 FROM   cte b
                 WHERE  a.name1 = b.name1
                        AND rn <> 1
                 ORDER  BY st
                 FOR XML PATH ('')) AS Ordered_String
FROM   cte a
WHERE  rn <> 1 

<强>结果

Ordered_String
--------------
abcdef
pqxyz