SQL Pivot总和具有特定条件

时间:2015-10-21 07:43:40

标签: sql-server sql-server-2008 pivot

我正在尝试创建一个数据透视表,以便将特定月份总计为总数,下面是我的表和sql枢轴:

CREATE TABLE yt
([Store] varchar(10), [Month] varchar(10), [xCount] int)
;

INSERT INTO yt
([Store], [Month], [xCount])
VALUES
('A', 'JAN', 1),
('A', 'FEB', 10),
('B', 'JAN', 2),
('B', 'FEB', 20),
('C', 'JAN', 3),
('C', 'FEB', 70),
('C', 'MAR', 110)    
;

    select *
    from 
    (
      select Store, Month, xCount
      from yt
    ) src
    pivot
    (
      sum(xcount)
      for Month in ([JAN], [FEB], [MAR])
    ) piv;

Store   JAN FEB MAR
A        1  10  NULL
B        2  20  NULL
C        3  70  110

以上结果我可以将当​​前月份的值相加。现在我想总结商店a的所有月份,仅存储商店b中的FEB和MAR,以及商店c总和MAR,所以我希望我的结果为

Store   JAN FEB MAR
A        6  100 110
B        5  90  110
C        3  70  110

我可以在枢轴中进行吗?或者需要创建一个表来再次运行sql? 谢谢你的帮助。

3 个答案:

答案 0 :(得分:2)

对于Sql Server 2008,您需要一些自我加入和排序来计算运行金额。在这里,我将商店作为这个订单:

WITH cte AS (SELECT * FROM @yt 
             PIVOT(SUM(xcount) FOR Month IN ([JAN], [FEB], [MAR])) piv)
SELECT  c1.Store ,
        SUM(c2.jan) AS jan ,
        SUM(c2.feb) AS feb ,
        SUM(c2.mar) AS mar
FROM    cte c1
        JOIN cte c2 ON c1.Store <= c2.Store
GROUP BY c1.Store

答案 1 :(得分:1)

您的问题是按商店desc运行总订单 在SQL Server2005 +中,您可以尝试:

SELECT Store,
    SUM([JAN]) OVER(ORDER BY Store DESC) AS [JAN],
    SUM([FEB]) OVER(ORDER BY Store DESC) AS [FEB],
    SUM([MAR]) OVER(ORDER BY Store DESC) AS [MAR]
FROM (
SELECT *
    FROM
    (
      SELECT Store, Month, xCount
      FROM yt
    ) src
    PIVOT
    (
      SUM(xcount)
      for Month in ([JAN], [FEB], [MAR])
    ) piv
) AS A
ORDER BY Store

但在MySQL中,您可以参考this link

答案 2 :(得分:0)

If you are using SQL SERVER 2012, you can use

SELECT STORE,
       SUM(JAN)
         OVER (
           ORDER BY RN DESC) JAN,
       SUM(FEB)
         OVER (
           ORDER BY RN DESC) FEB,
       SUM(MAR)
         OVER (
           ORDER BY RN DESC) MAR
FROM  (SELECT ROW_NUMBER()
                OVER (
                  ORDER BY STORE)RN,
              *
       FROM   (SELECT STORE,
                      MONTH,
                      XCOUNT
               FROM   #YT) SRC
              PIVOT ( SUM(XCOUNT)
                    FOR MONTH IN ([JAN],
                                  [FEB],
                                  [MAR]) ) PIV)A 
ORDER BY RN ASC