当没有值总和时,返回0总和--sql server

时间:2015-06-23 03:03:25

标签: sql sql-server sql-server-2008-r2 sum

如果这些列中没有任何值返回,则尝试返回0,在我的特定情况下,“过期”没有总值,因此返回,所以我在这里得到第二个片段的返回值。如果不计算值,我该如何归还?

SELECT ClientDeliveryStatus,
    SUM(CASE 
        WHEN ClientDeliveryStatus = 'Past Due' THEN 1 
        WHEN ClientDeliveryStatus = 'Due Tomorrow' THEN 1 
        WHEN ClientDeliveryStatus = 'Due Today' THEN 1 
        WHEN ClientDeliveryStatus = 'Due Beyond' THEN 1
        ELSE 0 END) AS Total
FROM Table1
GROUP BY ClientDeliveryStatus

当前结果:

    ClientDeliveryStatus    Total
    Due Beyond              1
    Due Today               3
    Due Tomorrow            51

期望的结果:

    ClientDeliveryStatus    Total
    Due Beyond              1
    Due Today               3
    Due Tomorrow            51
    Past Due                0

示例数据:

TABLE1:

ClientDeliveryStatus
Due Tomorrow
Due Tomorrow
Due Tomorrow
Due Beyond  
Due Beyond  
Due Tomorrow
Due Beyond
Due Beyond
Due Beyond
Due Today
Due Today

CREATE TABLE1 Table1 (ClientDeliveryStatus VARCHAR(MAX))
INSERT INTO Table1 Values ('Due Tomorrow'), ('Due Tomorrow'), ('Due Tomorrow'), ('Due Beyond'), ('Due Beyond'), ('Due Beyond'), ('Due Beyond'), ('Due Today'),('Due Today')

1 个答案:

答案 0 :(得分:3)

您需要一张包含所有状态的表格。如果您还没有表,可以在查询中执行此操作:

SELECT ClientDeliveryStatus, COUNT(t.ClientDeliveryStatus) AS Total
FROM (SELECT 'Past Due' as cds UNION ALL
      SELECT 'Due Tomorrow' UNION ALL
      SELECT 'Due Today' UNION ALL
      SELECT 'Due Beyond'
     ) s LEFT JOIN
     Table t
     ON s.cds = t.ClientDeliveryStatus
GROUP BY s.cds;

您的原始查询不正确,因为GROUP BYCASE中的SUM()而错过select * from table where date(convert_tz(date, 'UTC', 'EST')) == date('2014-03-08'); 并且过于复杂。