3

在我的 SQL CE 数据库中,我有三个表:customerlist(和之间customerlist的联结表- 因为它是多对多关系)。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 的任何想法?

4

2 回答 2

2

使用LEFT JOINwithISNULL替换NULL为 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 小提琴演示


更新

对于 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;
于 2013-02-20T09:58:35.903 回答
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
于 2013-02-20T10:00:00.407 回答