SQL返回一列为0的行

Sha*_*nov 1 sql t-sql sql-server-2008

我有一个发布文章的网站,并为某些文章分配了位置和个人资料,因此只有该位置和相关个人资料中的人才能看到它.

我有一个查询,它返回分配给该位置的文章的位置和计数

SELECT locations.id, locations.location, COUNT( DISTINCT article.id) AS Number 
FROM ar.locations 
JOIN ar.articleLocation 
     ON articleLocation.locationId = locations.id 
JOIN ar.article 
     ON article.id=articleLocation.articleId 
JOIN ar.articleProfile 
     ON article.id = articleProfile.articleId 
WHERE article.createDate >= '2013-11-30' 
AND article.startDate <= '2014-05-30' 
AND articleProfile.profileId 
     IN ('1000000410','1000000408','1000000393') 
AND articleLocation.locationId IN ('250','194','195','204','281') 
GROUP BY locations.id, locations.location 
ORDER BY locations.location
Run Code Online (Sandbox Code Playgroud)

这将返回结果

id  location    Number
194 LocationA     1
250 LocationB    16
281 LocationC     2
Run Code Online (Sandbox Code Playgroud)

但在查询中还有2个其他位置ID,并且因为没有分配给这些位置的文章,所以没有为这些IDS返回任何内容

理想情况下我想

    id  location    Number
    194 LocationA     1
    250 LocationB    16
    281 LocationC     2
    204 LocationD     0
    195 LocationE     0
Run Code Online (Sandbox Code Playgroud)

如果该位置没有文章,我似乎无法弄清楚如何带回0.任何正确方向的帮助/指针都将非常感激.如果有更有效/更好的方式来做我目前正在做的事情,我也不仅仅接受建议.

Jos*_*h B 5

您可以使用a LEFT JOIN来实现此目的,如下所示.括号未正确定位,已在下面更正.

SELECT locations.id, locations.location, COALESCE(COUNT( DISTINCT article.id), 0) AS Number 
FROM ar.locations 
JOIN ar.articleLocation 
     ON articleLocation.locationId = locations.id 
LEFT JOIN 
(SELECT article.* FROM ar.article 
JOIN ar.articleProfile 
     ON article.id = articleProfile.articleId 
WHERE article.createDate >= '2013-11-30' 
AND article.startDate <= '2014-05-30' 
AND articleProfile.profileId 
     IN ('1000000410','1000000408','1000000393') 
) article
ON article.id=articleLocation.articleId 
WHERE articleLocation.locationId IN ('250','194','195','204','281') 
GROUP BY locations.id, locations.location 
ORDER BY locations.location;
Run Code Online (Sandbox Code Playgroud)

如果没有记录(而不是返回NULL),COALESCE函数将打印0.

参考文献:

在TechNet上使用外部联接

MSDN上的COALESCE(Transact-SQL)