在我的SQL CE数据库我有三个表:customer,list和customerlist(之间的结台customer和list-因为它是一个多一对多的关系)。
customer
list
customerlist
我正在尝试运行一个查询,该查询将显示所有当前列表以及当前已订阅该列表(从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有什么想法吗?
使用LEFT JOIN代替withISNULL替换NULL为0:
LEFT JOIN
ISNULL
NULL
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小提琴演示
对于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;