基于条件的不同列的SQL总和值

时间:2013-12-19 12:21:38

标签: sql sql-server tsql

以下是我在表格中的数据:

Date           Original    Estimated     Actual
2013-04-14     141.44323    NULL          384.875
2013-04-14     31.184295    NULL          200.375
2013-04-14     0            NULL          54.75
2013-04-14     0            NULL          0.625
2013-04-15     5.4326204    NULL          0
2013-04-15     45.795869    NULL          -0.375
2013-04-15     86.57694     NULL          11.875
2013-04-15     186.219      NULL          58.875

我希望对列实际的值求和,但如果其值为零或为null,则该特定行值应取自估计列,如果估算列的值也为零,则值将从原始列中获取。我希望结果按月和年分组。请帮忙

4 个答案:

答案 0 :(得分:2)

SELECT
    SELECT DATEPART(YEAR, Date) as [Year],
    DATEPART(MONTH, Date) as [Month],
    SUM(COALESCE(NULLIF(Actual,0), NULLIF(Estimated, 0), Original)
FROM YourTable
GROUP BY DATEPART(YEAR, Date), DATEPART(MONTH, Date);

答案 1 :(得分:2)

我相信你想要COALESCE

<德尔>     SELECT DATEPART(年,日期),DATEPART(月,日期),            SUM(Coalesce(Actual,Estimated,Original))     来自MyTable     GROUP BY DATEPART(年,日期),DATEPART(月,日);

编辑正如@MartinSmith指出的那样,NULL OR Zero需要照顾。这可以通过在通过COALESCE运行之前使用CTE将零回调为NULL来完成,如下所示:

   WITH CTE AS
   (
      SELECT 
          CASE WHEN Actual = 0 THEN NULL ELSE Actual END AS Actual,
          CASE WHEN Estimated = 0 THEN NULL ELSE Estimated END AS Estimated,
          CASE WHEN Original = 0 THEN NULL ELSE Original END AS Original
      FROM MyTable
   )
    SELECT DATEPART(YEAR, Date), DATEPART(MONTH, Date), 
           SUM(Coalesce(Actual, Estimated, Original)) 
    FROM CTE
    GROUP BY 
       DATEPART(YEAR, Date), DATEPART(MONTH, Date);

答案 2 :(得分:0)

NullIf是Tomas Greif建议的最佳解决方案。更正后的代码:

declare @data table (
    [Date] datetime not null, 
    [Original] decimal(18,9) null, 
    [Estimated] decimal(18,9) null, 
    [Actual] decimal(18,9) null);

insert into @data
    ([Date],           [Original],   [Estimated],    [Actual])
values 
    ('2013-04-14',     141.44323,    NULL,          384.875),
    ('2013-04-14',     31.184295,    NULL,          200.375),
    ('2013-04-14',     0,            NULL,          54.75),
    ('2013-04-14',     0,            NULL,          0.625),
    ('2013-04-15',     5.4326204,    NULL,          0),
    ('2013-04-15',     45.795869,    NULL,          -0.375),
    ('2013-04-15',     86.57694,     NULL,          11.875),
    ('2013-04-15',     186.219,      NULL,          58.875);

select 
    [DateMonth] = dateAdd(month, dateDiff(month, 0, [Date]), 0),
    [SumMonth]  = SUM(COALESCE(NULLIF(Actual,0),NULLIF(Estimated,0),Original))
from @data
group by dateAdd(month, dateDiff(month, 0, [Date]), 0)

答案 3 :(得分:0)

使用nullif怎么样?这将比CASE声明短得多。

select 
   DATEPART(YEAR, Date),
   sum(coalesce(nullif(Actual,0),nullif(Estimate,0),Original))
from
   MyTable
group by
   DATEPART(YEAR, Date);