我无法让列在 SQL 中进行透视。我想将前 6 个结果从一列转换为一行。我正在旋转的列可以从少于或多于 6 个结果开始,但我想忽略前 6 名之外的任何内容。
我的 Table1 看起来像这样:
ID | GroupID | CodeNum
----------------------
1 | 1 | 111
2 | 1 | 222
3 | 1 | 333
4 | 1 | 444
5 | 1 | 555
6 | 1 | 666
7 | 1 | 777
8 | 2 | 111
9 | 2 | 888
10 | 3 | 999
我希望我的输出看起来像这样:
GroupID | Code1 | Code2 | Code3 | Code4 | Code5 | Code6
-------------------------------------------------------
1 | 111 | 222 | 333 | 444 | 555 | 666
2 | 111 | 888 | | | |
3 | 999 | | | | |
我试过这段代码:
SELECT GroupID
, [Code1] = CASE WHEN rn = 1 THEN CodeNum END
, [Code2] = CASE WHEN rn = 2 THEN CodeNum END
, [Code3] = CASE WHEN rn = 3 THEN CodeNum END
, [Code4] = CASE WHEN rn = 4 THEN CodeNum END
, [Code5] = CASE WHEN rn = 5 THEN CodeNum END
, [Code6] = CASE WHEN rn = 6 THEN CodeNum END
FROM (
SELECT TOP 6 GroupID
, rn = ROW_NUMBER() OVER (ORDER BY ID)
, CodeNum
FROM Table1
) q
GROUP BY
GroupID
但我收到一个错误,上面写着Column 'q.rn' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
当 CodeNum 每个 GroupID 可以有 1 到 12 个值时,有没有办法做到这一点?