2013-04-08 41 views
0

我無法讓列在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之間時,有沒有辦法做到這一點?

回答

4

由於您使用的是GROUP BY,因此您需要對SELECT中的所有項目進行分組或使用聚合函數。

你將要使用將得到的結果如下,然後支點行入列:

SELECT GroupID 
     , [Code1] = max(CASE WHEN rn = 1 THEN CodeNum END) 
     , [Code2] = max(CASE WHEN rn = 2 THEN CodeNum END) 
     , [Code3] = max(CASE WHEN rn = 3 THEN CodeNum END) 
     , [Code4] = max(CASE WHEN rn = 4 THEN CodeNum END) 
     , [Code5] = max(CASE WHEN rn = 5 THEN CodeNum END) 
     , [Code6] = max(CASE WHEN rn = 6 THEN CodeNum END) 
FROM  
(
    SELECT GroupID 
    , rn = ROW_NUMBER() OVER (PARTITION BY GroupID ORDER BY ID) 
    , CodeNum 
    FROM Table1  
) q 
GROUP BY GroupID 

SQL Fiddle with Demo

你會發現,我刪除了TOP 6,並添加了partition by GroupId。如果您使用TOP,那麼您將只返回第一個ID的值。分區將返回每個ID的行,但外層選擇只返回前6行。

這給出結果:

| GROUPID | CODE1 | CODE2 | CODE3 | CODE4 | CODE5 | CODE6 | 
---------------------------------------------------------------- 
|  1 | 111 | 222 | 333 | 444 | 555 | 666 | 
|  2 | 111 | 888 | (null) | (null) | (null) | (null) | 
|  3 | 999 | (null) | (null) | (null) | (null) | (null) | 

注意,根據您的SQL Server版本,這也可以使用PIVOT功能寫着:

select GroupID, 
    [1] as Code1, 
    [2] as Code2, 
    [3] as Code3, 
    [4] as Code4, 
    [5] as Code5, 
    [6] as Code6 
from 
(
    SELECT GroupID 
    , rn = ROW_NUMBER() OVER (PARTITION BY GroupID ORDER BY ID) 
    , CodeNum 
    FROM Table1  
) d 
pivot 
(
    max(codenum) 
    for rn in ([1], [2], [3], [4], [5], [6]) 
) piv; 

SQL Fiddle with Demo

相關問題