sql 以多个值为中心

sql pivot on multiple values

给定以下数据table

   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 的总和?

你可以这样做:

测试数据

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