多个值上的sql pivot

时间:2015-03-05 10:55:37

标签: sql sql-server pivot

给出以下数据表

   Id   Code    Date                    PIVOT VALUE1    VALUE2
    1   WMAZ    2014-01-31 12:23:06.000 1     103            1
    2   EEEE    2014-01-31 11:59:15.000 2     74             2
    3   WMAZ    2014-01-31 11:59:10.000 1     3              3
    4   WMAZ    2014-01-31 11:56:55.000 2     10             4
    5   WMAZ    2014-01-31 11:56:14.000 2     96             5
    6   EEEE    2014-01-31 11:55:26.000 2     159            6

我需要透视数据才能得到这个:

Code Date        SUMVALUE1FORPIVOT1 SUMVALUE1FORPIVOT2 SUMVALUE2FORPIVOT1 SUMVALUE2PIVOT2
WMAZ 2014-01-31  (103+3)            (10+96)            (1+3)              (4+5)
EEEE 2014-01-31  NULL               (74+159)           NULL               (6+2)

我如何获得按代码和日期分组的每个数据透视表的value1和value2的总和,而不为每个字段编写子查询?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

测试数据

DECLARE @tbl TABLE(Id INT,Code VARCHAR(100),
                   Date DATETIME,
                   [PIVOT] INT, 
                   VALUE1 INT,
                   VALUE2 INT)
INSERT INTO @tbl
VALUES
(1,'WMAZ','2014-01-31 12:23:06.000',1,103,1),
(2,'EEEE','2014-01-31 11:59:15.000',2,74,2),
(3,'WMAZ','2014-01-31 11:59:10.000',1,3,3),
(4,'WMAZ','2014-01-31 11:56:55.000',2,10,4),
(5,'WMAZ','2014-01-31 11:56:14.000',2,96,5),
(6,'EEEE','2014-01-31 11:55:26.000',2,159,6)

<强>查询

SELECT
    tbl.Code,
    CAST(tbl.Date AS DATE) AS Date,
    SUM(CASE WHEN [PIVOT]=1 THEN VALUE1 ELSE NULL END) AS SUMVALUE1FORPIVOT1,
    SUM(CASE WHEN [PIVOT]=2 THEN VALUE1 ELSE NULL END) AS SUMVALUE1FORPIVOT2,
    SUM(CASE WHEN [PIVOT]=1 THEN VALUE2 ELSE NULL END) AS SUMVALUE2FORPIVOT1,
    SUM(CASE WHEN [PIVOT]=2 THEN VALUE2 ELSE NULL END) AS SUMVALUE2FORPIVOT2
FROM
    @tbl AS tbl
GROUP BY 
    tbl.Code,
    CAST(tbl.Date AS DATE)
ORDER BY 
    tbl.Code DESC

<强>结果:

Code    Date          SUMVALUE1FORPIVOT1    SUMVALUE1FORPIVOT2  SUMVALUE2FORPIVOT1  SUMVALUE2PIVOT2
---------------------------------------------------------------------------------------------------
WMAZ    2014-01-31    106                   106                 4                   9
EEEE    2014-01-31    NULL                  233                 NULL                8