SQL按字段加入*可能*为空

时间:2013-02-20 09:57:19

标签: sql sql-server-ce

在我的SQL CE数据库中,我有三个表:customerlistcustomerlistcustomerlist之间的联结表 - 因为它是多对多的关系。)

我正在尝试运行一个查询,该查询将显示所有当前列表以及当前订阅该列表的客户数量(从customerlist表开始计算)。

这是我当前的查询:

select list.listid, count(customerlist.customerid) as numppl, list.ShortDesc
from list inner join customerlist on list.listid=customerlist.listid
group by list.ShortDesc, list.listid
order by numppl desc

此数据库的当前结构是:

[Customer]           [List]             [CustomerList]
CustomerId           ListId             CustomerListId
Name                 ShortDesc          CustomerId
Other details                           ListId

这将返回当前已分配给客户的所有列表 - 但不会返回空的列表。空列表被隐藏。

我想修改此查询以显示空列表,但我正在努力。我想要的输出是:

Name      numppl
listA     375
listB     45
listC     0

(在上面的例子中,当前没有返回listC。)

有关如何在查询中显示listC的任何想法吗?

2 个答案:

答案 0 :(得分:2)

使用LEFT JOIN代替ISNULLNULL替换为0:

SELECT 
  list.listid, 
  ISNULL(count(customerlist.customerid), 0) AS numppl, 
  list.ShortDesc
FROM list 
LEFT JOIN customerlist ON list.listid = customerlist.listid
GROUP BY list.ShortDesc, 
         list.listid
ORDER BY numppl DESC;

SQL Fiddle Demo


更新

对于SQL Server CE,请尝试以下操作:

SELECT 
  list.listid, 
  SUM(CASE WHEN customerlist.customerid IS NULL THEN 0 ELSE 1 END) AS numppl, 
  list.ShortDesc
FROM list 
LEFT JOIN customerlist ON list.listid = customerlist.listid
GROUP BY list.ShortDesc, 
         list.listid
ORDER BY numppl DESC;

答案 1 :(得分:0)

您必须使用LEFT JOIN语法。

select list.listid,  case when count(customerlist.customerid) is null then 0 else count(customerlist.customerid) end as numppl, list.ShortDesc
from list left join customerlist on list.listid=customerlist.listid
group by list.ShortDesc, list.listid
order by numppl desc

或者您可以使用RIGHT JOIN

select list.listid, case when count(customerlist.customerid) is null then 0 else count(customerlist.customerid) end as numppl, list.ShortDesc
from customerlist right join list on customerlist.listid=list.listid
group by list.ShortDesc, list.listid
order by numppl desc

使用COALESCE:

select list.listid,  coalesce(count(customerlist.customerid),0) as numppl, list.ShortDesc
from list left join customerlist on list.listid=customerlist.listid
group by list.ShortDesc, list.listid
order by numppl desc