SQL中的条件SUM

时间:2018-05-08 07:05:38

标签: sql group-by case

我想计算con_Amount字段&想要在Con_PubDate的条件下将总数放到D01,D02,...... D31。 如果Con_PubDate字段Day = 1那么我想将总数设为D01,如果Con_PubDate字段Day = 2那么我想将总数设为D02,同样直到Day = 31然后我想将总数设为D31

我尝试在存储过程中使用代码但是它有错误。有人请帮我解决这个问题。

SELECT Con_Cnt_Code,
       Con_Dst_Code,
       Con_Cor_Code,
       SUM(CASE
            WHEN DATEPART(DAY,Con_PubDate) = 1 THEN con_Amount
       ELSE
            SUM(CASE
                WHEN DATEPART(DAY,Con_PubDate) = 2 THEN con_Amount
            ELSE
                 SUM(CASE
                WHEN DATEPART(DAY,Con_PubDate) = 31 THEN con_Amount
                END) AS D31
            END) AS D02
        END) AS D01
 FROM Contributions 
 GROUP BY Con_Cnt_Code,Con_Dst_Code,Con_Cor_Code

1 个答案:

答案 0 :(得分:1)

您可能希望CASE表达式的每个条件总和作为选择列表中的单独项目,如下所示:

SELECT
    Con_Cnt_Code,
    Con_Dst_Code,
    Con_Cor_Code,
    SUM(CASE WHEN DATEPART(DAY,Con_PubDate) = 1  THEN con_Amount END) AS D01,
    SUM(CASE WHEN DATEPART(DAY,Con_PubDate) = 2  THEN con_Amount END) AS D02,
    -- and possibly other days as well
    SUM(CASE WHEN DATEPART(DAY,Con_PubDate) = 31 THEN con_Amount END) AS D31
FROM Contributions
GROUP BY
    Con_Cnt_Code, Con_Dst_Code, Con_Cor_Code;

默认情况下,SUM会忽略NULL个值,因此您的ELSE表达式中可能不需要CASE条件。如果你添加一个,你可以默认金额总和为零。