如何在SQL中使用Count返回0而不是没有行

时间:2016-02-23 21:01:54

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

I have a query:

SELECT     Store_Number, COALESCE (COUNT(Invoice_Number), 0) AS abc
FROM        Invoice_Detail_Tb
WHERE     (Invoice_Date BETWEEN @start AND @end) AND (Invoice_Detail_Code IN ('abc'))
GROUP BY Store_Number

它回来了:

Store Number       ABC
1                  1
3                  23
4                  24
5                  7

我希望它能够回归:

Store Number       ABC
1                  1
2                  0
3                  23
4                  24
5                  7

我因为我的" Group By"而假设它。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:5)

最简单的方法。 。 。如果有效。 。 。是使用条件聚合而不是where子句。因此,如果所有商店都在数据中,但他们可能没有“abc”,那么

SELECT Store_Number, SUM(Invoice_Detail_Code = 'abc' THEN 1 ELSE 0 END) AS abc
FROM Invoice_Detail_Tb
WHERE Invoice_Date BETWEEN @start AND @end
GROUP BY Store_Number;

更一致地工作的方法假设您有一个Stores表,其中包含商店。那你只需要一个LEFT OUTER JOIN

SELECT s.Store_Number, COUNT(id.Store_Number) AS abc
FROM Stores s LEFT OUTER JOIN
     Invoice_Detail_Tb id
     ON s.Store_Number = id.Store_Number AND
        id.Invoice_Date BETWEEN @start AND @end AND
        id.Invoice_Number = 'abc'
GROUP BY s.Store_Number;