基于单列的多个Pivot

时间:2015-02-12 06:37:45

标签: sql sql-server sql-server-2012 pivot

请考虑以下表格:

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

我想创建此结果:

Year   Month    T1_Value    T1_IsUpdate     T2_Value    T2_IsUpdate     T3_Value    T3_IsUpdate
----------------------------------------------------------------------------------------------
2011     1       1000            0           5000            1           11000           1
2012     1       2000            0           500             0           800             1

是否可以使用PIVOT创建此内容?

由于

1 个答案:

答案 0 :(得分:0)

这是使用动态交叉表完成的。供参考:http://www.sqlservercentral.com/articles/Crosstab/65048/

CREATE TABLE Temp(
    ID          INT,
    [Year]      INT,
    [Month]     INT,
    [Type]      VARCHAR(5),
    Value       INT,
    IsUpdate    BIT
)
INSERT INTO Temp VALUES
(1, 2011, 1, 'T1', 1000, 0),
(2, 2012, 1, 'T1', 2000, 0),
(3, 2011, 1, 'T2', 5000, 1),
(4, 2012, 1, 'T2', 500, 0),
(5, 2011, 1, 'T3', 11000, 1),
(6, 2012, 1, 'T3', 800, 1);

DECLARE @sql1 VARCHAR(4000) = ''
DECLARE @sql2 VARCHAR(4000) = ''
DECLARE @sql3 VARCHAR(4000) = ''

SELECT @sql1 = 
'SELECT
     [Year]
    ,[Month]'
+ CHAR(10)

SELECT @sql2 = @sql2 +
'   ,MAX(CASE WHEN [Type] = ''' + [Type] + ''' THEN Value END) AS [' + [Type] + '_Value]' + CHAR(10) +
'   ,MAX(CASE WHEN [Type] = ''' + [Type] + ''' THEN CAST(IsUpdate AS INT) END) AS [' + [Type] + '_IsUpdate]' + CHAR(10)
FROM(
    SELECT DISTINCT [Type] FROM Temp
)t
ORDER BY [Type]

SELECT @sql3 = 
'FROM Temp
GROUP BY [Year], [Month]
ORDER BY [Year], [Month]'

PRINT(@sql1 + @sql2 + @sql3)
EXEC(@sql1 + @sql2 + @sql3)

DROP TABLE Temp

<强> RESULT

Year        Month       T1_Value    T1_IsUpdate T2_Value    T2_IsUpdate T3_Value    T3_IsUpdate
----------- ----------- ----------- ----------- ----------- ----------- ----------- -----------
2011        1           1000        0           5000        1           11000       1
2012        1           2000        0           500         0           800         1