我無法讓列在SQL中進行透視。我想將一列中的前6個結果轉換爲一行。我樞轉列可以有少於或多於6個結果開始,但我想忽略任何超出前6獲取列中的前6個項目以轉到SQL中的某一行
我的表1是這樣的:
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
但我剛開g出現錯誤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之間時,有沒有辦法做到這一點?