简体   繁体   English

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

[英]Return 0 in sum when no values to sum - sql server

Trying to return 0 if any of these columns have no values returned, in my particular case 'Past Due' has no values to total, so it is returned, so i get the return in the second snippet here.如果这些列中的任何一列没有返回值,则尝试返回 0,在我的特定情况下,“过期”没有总计的值,因此它被返回,因此我在此处的第二个片段中获得了返回值。 How can I return something if these are no values to count?如果这些都不是可计算的值,我该如何返回?

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

Current Result:当前结果:

    ClientDeliveryStatus    Total
    Due Beyond              1
    Due Today               3
    Due Tomorrow            51

Desired Result:预期结果:

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

Example data:示例数据:

TABLE1:表格1:

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')

You need a table of all the statuses.您需要一个包含所有状态的表格。 If you don't already have a table, you can do this in the query itself:如果您还没有表,则可以在查询本身中执行此操作:

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;

Your original query is incorrect because it is missing a GROUP BY and overly complicated because of the CASE in the SUM() .您的原始查询不正确,因为它缺少GROUP BY并且由于SUM()中的CASE而过于复杂。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM