我想将查询中的单列结果拆分为 4 列:
样本来源: ( Select [FirstName from User
)
Peter
Mary
John
Tina
Carl
Jane
Bill
Sarah
我想看起来像这样:
Column1 Column2 Column3 Column4
Peter Mary John Tina
Carl Jane Bill Sarah
我想将查询中的单列结果拆分为 4 列:
样本来源: ( Select [FirstName from User
)
Peter
Mary
John
Tina
Carl
Jane
Bill
Sarah
我想看起来像这样:
Column1 Column2 Column3 Column4
Peter Mary John Tina
Carl Jane Bill Sarah
您需要有一个独特的列来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