我有一张这样的表:
Acct MasterAcct
------- -------------
123 M01
123 M02
234 M03
345 M04
456 M05
456 M06
456 M07
我想将MasterAcct列分为三列(Master1,Master2,Master3)。一个帐户最多可以有三个与之关联的主帐户。上一个表的示例输出在一行上有#456帐户,然后在Master1,Master2和Master3中有三个主帐号。有人可以帮忙吗?
答案 0 :(得分:1)
您可以将PIVOT
与ROW_NUMBER()
排名功能结合使用。
SELECT Acct, [1] as [Master1], [2] as [Master2], [3] as [Master3]
FROM
(
SELECT Acct,
MasterAcct,
ROW_NUMBER() OVER(PARTITION BY acct ORDER BY MasterAcct) as mid
FROM tbl
) as t
PIVOT
(
MIN(MasterAcct)
FOR mid IN ([1], [2], [3])
) as p
<强> SQL FIDDLE DEMO 强>
您可以在不使用PIVOT
的情况下获得相同的结果。以下查询很容易理解。
SELECT
Acct,
MAX(CASE WHEN mid=1 THEN MasterAcct END) as [Master1],
MAX(CASE WHEN mid=2 THEN MasterAcct END) as [Master2],
MAX(CASE WHEN mid=3 THEN MasterAcct END) as [Master3]
FROM
(
SELECT Acct,
MasterAcct,
ROW_NUMBER() OVER(PARTITION BY acct ORDER BY MasterAcct) as mid
FROM tbl
) t
GROUP BY Acct
<强> SQL FIDDLE DEMO 强>