2015-02-10 176 views
0

請考慮此表:樞軸返回null基於列值

Id  Year  Month  Type  Value 
------------------------------------------ 
1  2011  1   T1  1000 
2  2012  1   T1  2000 
3  2011  1   T2  5000 
4  2012  1   T2  500 
5  2011  1   T3  11000 
6  2012  1   T3  800 

我想創建這樣的結果:

Id  Year  Month  T1  T2  T3 
------------------------------------------------ 
1  2011  1   1000 5000 11000 
2  2012  1   2000 500  800 

我想基於TYPE列中使用PIVOT它的價值和我寫了這個腳本:

SELECT [Year],[Month], [T1],[T2],[T3] 
FROM (SELECT [Year],[Month],Value,[Type] 
     FROM MyTable 
    ) p 
PIVOT (MAX(VALUE) FOR [Type] IN ([[T1],[T2],[T3])) AS pvt 

但是這個腳本生成6行像這樣:

Id  Year  Month  T1  T2  T3 
------------------------------------------------ 
1  2011  1   1000 Null Null 
2  2012  1   2000 Null Null  
3  2011  1   Null 5000 Null 
4  2012  1   Null 500  Null 
5  2011  1   Null Null 11000 
6  2012  1   Null Null 800 

我該如何合併這個結果?

感謝

回答

2

你可以試試這個:

DECLARE @t TABLE 
    (
     ID INT , 
     Year INT , 
     Month INT , 
     Type CHAR(2) , 
     Value INT 
    ) 

INSERT INTO @t 
VALUES (1, 2011, 1, 'T1', 1000), 
     (2, 2012, 1, 'T1', 2000), 
     (3, 2011, 1, 'T2', 5000), 
     (4, 2012, 1, 'T2', 500), 
     (5, 2011, 1, 'T3', 11000), 
     (6, 2012, 1, 'T3', 800); 
WITH cte 
      AS (SELECT t1.Year , 
         t1.Month , 
         t1.Value AS T1 , 
         t2.Value AS T2 , 
         t3.Value AS T3 , 
         ROW_NUMBER() OVER (PARTITION BY t1.Year, t1.Month ORDER BY t1.ID, t2.ID, t3.ID) AS rn , 
         DENSE_RANK() OVER (ORDER BY t1.ID) AS ID 
       FROM  @t t1 
         JOIN @t t2 ON t1.Type <> t2.Type 
         JOIN @t t3 ON t1.Type <> t3.Type AND t2.Type <> t3.Type 
       WHERE t1.Year = t2.Year 
         AND t1.Year = t3.Year 
         AND t1.Month = t2.Month 
         AND t1.Month = t2.Month 
      ) 
    SELECT ID, Year, Month, T1, T2, T3 
    FROM cte 
    WHERE rn = 1 

輸出:

ID Year Month T1 T2 T3 
1 2011 1  1000 5000 11000 
2 2012 1  2000 500 800 

但你的代碼不一樣的,因爲YearMonth將在行消除,Type變傳播元素和Value是聚合元素。

我懷疑你在你的表表達式具有ID:

FROM (SELECT [Year],[Month],Value,[Type],[ID] 
     FROM MyTable 
    ) p 

在這種情況下,分組元素通過消除變得YearMonthID! 這就是爲什麼你得到所有6行。

DECLARE @t TABLE 
    (
     ID INT , 
     Year INT , 
     Month INT , 
     Type CHAR(2) , 
     Value INT 
    ) 

INSERT INTO @t 
VALUES (1, 2011, 1, 'T1', 1000), 
     (2, 2012, 1, 'T1', 2000), 
     (3, 2011, 1, 'T2', 5000), 
     (4, 2012, 1, 'T2', 500), 
     (5, 2011, 1, 'T3', 11000), 
     (6, 2012, 1, 'T3', 800); 

SELECT [Year],[Month], [T1],[T2],[T3] 
FROM (SELECT [Year],[Month],Value,[Type] 
     FROM @t 
    ) p 
PIVOT (MAX(VALUE) FOR [Type] IN ([T1],[T2],[T3])) AS pvt 

輸出:

Year Month T1 T2 T3 
2011 1  1000 5000 11000 
2012 1  2000 500 800