SQL单柱拆分成多列(SQL single column split over multiple c

2019-09-19 05:29发布

我想将单列结果从查询拆分成4列:

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

法案
莎拉

我想是这样的:

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

Answer 1:

你需要有一个独特的列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


Answer 2:

在这里,您有选项吨,寻找一个更适合你的情况: 从值的列表中创建列

上一页链接引导到更多的信息



文章来源: SQL single column split over multiple columns