请考虑此表:
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
我想在PIVOT
列上根据它的值使用TYPE
,我写了这个脚本:
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
如何合并此结果?
感谢
答案 0 :(得分: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
但是您的代码也是如此,因为Year
和Month
将通过消除成行,Type
成为扩展元素,Value
是聚合元素。
我怀疑你的表格中有ID:
FROM (SELECT [Year],[Month],Value,[Type],[ID]
FROM MyTable
) p
在这种情况下,分组元素通过消除变为Year
,Month
和ID
!
这就是为什么你得到所有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