在SQL Server中显示COUNT = 0的行

时间:2011-07-07 19:21:42

标签: sql sql-server tsql

以下查询仅返回已有订单的区域的区域名称。

   SELECT r.RegionName,
          COUNT (DISTINCT o.uid)
     FROM Orders AS o
LEFT JOIN Customers AS c ON o.CustomerID = c.uid
LEFT JOIN Regions AS r ON c.Region = r.uid
    WHERE (r.RegionName NOT LIKE 'NULL') 
      AND (r.RegionName <> '') 
      AND (r.RegionName NOT LIKE 'Region 1') 
      AND (o.DateOrdered LIKE '7%2011%')
 GROUP BY r.RegionName
 ORDER BY r.RegionName

如何修改它,以便即使“COUNT”为“0”时所有地区名称都会显示?

1 个答案:

答案 0 :(得分:6)

您需要将JOIN更改为区域RIGHT JOIN或将区域设为FROM表,然后将JOIN更改为其他表格。

我更喜欢第二种方法,因为它对我来说似乎更直观。您关心的是这里的区域,并且您正在尝试获取有关区域的信息,因此应该在FROM(IMO)中:

SELECT
    R.RegionName,
    COUNT(O.uid)
FROM
    Regions R
LEFT OUTER JOIN Customers C ON C.Region = R.uid  -- I really don't like this naming convention
LEFT OUTER JOIN Orders O ON
    O.CustomerID = C.uid AND
    O.DateOrdered LIKE '7%2011%'  -- Is your date really stored as a string? Ugh!
WHERE
    R.RegionName <> 'NULL' AND   -- This is VERY bad...
    R.RegionName <> '' AND
    R.RegionName <> 'Region 1'
GROUP BY
    R.RegionName
ORDER BY
    R.RegionName