我正在尝试将行组转置为多列。
到目前为止,我已经能够使用xml路径将一组行聚合到单个列中,但是我需要将更多数据保留到更多列中。
CntTyp表(联系方式)
| ContactID | CatCode | CatDesc |
|-----------|---------|---------|
| 89 | 26 | OA |
| 89 | 27 | OA2 |
| 90 | 26 | OA |
| 91 | 26 | OA |
| 91 | 1625 | Donor |
| 91 | 1625 | Player |
所需的输出
| ContactID | CatCode | CatDesc | CatCode | CatDesc | CatCode | CatDesc |
|-----------|---------|---------|---------|---------|---------|---------|
| 89 | 26 | OA | 27 | OA2 | | |
| 90 | 26 | OA | | | | |
| 91 | 26 | OA | 1625 | Donor | 234 | Player |
我的代码:
select ContactID, catInfo =
STUFF((select ','+cast(t1.CatCode as varchar)
from CntTyp t1 where t.ContactID = t1.ContactID
for xml path ('')), 1, 1, '')
from CntTyp t
group by ContactID
我的输出
| ContactID | catInfo |
|-----------|-------------|
| 89 | 26,27 |
| 90 | 26 |
| 91 | 26,1625,234 |
答案 0 :(得分:4)
我们可以尝试在ROW_NUMBER
的帮助下进行数据透视查询:
WITH cte AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY ContactID ORDER BY CatCode, CatDesc) rn
FROM CntTyp
)
SELECT
ContactID,
MAX(CASE WHEN rn = 1 THEN CatCode END) AS CatCode1,
MAX(CASE WHEN rn = 1 THEN CatDesc END) AS CatDesc1,
MAX(CASE WHEN rn = 2 THEN CatCode END) AS CatCode2,
MAX(CASE WHEN rn = 2 THEN CatDesc END) AS CatDesc2,
MAX(CASE WHEN rn = 3 THEN CatCode END) AS CatCode3,
MAX(CASE WHEN rn = 3 THEN CatDesc END) AS CatDesc3
FROM cte
GROUP BY
ContactID;