SQL单列拆分多列

时间:2012-07-09 08:21:32

标签: sql sql-server-2008

我想将查询中的单列结果拆分为4列:

示例来源:(Select [FirstName from User
彼得
玛丽
约翰
蒂娜
卡尔

比尔
萨拉

我想看起来像这样:

Column1   Column2   Column3   Column4  
Peter     Mary      John      Tina  
Carl      Jane      Bill      Sarah

2 个答案:

答案 0 :(得分:8)

您需要为ORDER BY添加一个唯一列才能获得确定性结果,但这些内容应该有效。

;WITH T
     AS (SELECT [FirstName],
                ( ROW_NUMBER() OVER (ORDER BY (SELECT 0)) - 1 ) / 4 AS Row,
                ( ROW_NUMBER() OVER (ORDER BY (SELECT 0)) - 1 ) % 4 AS Col
         FROM   [User])
SELECT [0] AS Column1,
       [1] AS Column2,
       [2] AS Column3,
       [3] AS Column4
FROM   T PIVOT (MAX(name) FOR Col IN ([0], [1], [2], [3])) P 
ORDER BY Row

答案 1 :(得分:1)

在这里你有很多选择,寻找一个更适合你的情况: Create columns from list of values

上一个链接指向even more information