SQL按*可能*为空的字段联接
在我的SQL CE数据库中,我有三个表:SQL按*可能*为空的字段联接,sql,sql-server-ce,Sql,Sql Server Ce,在我的SQL CE数据库中,我有三个表:customer、list和customerlist(customer和list之间的连接表,因为它是多对多关系) 我正在尝试运行一个查询,该查询将显示所有当前列表以及当前订阅该列表的客户数(从customerlist表中计算) 以下是我当前的查询: select list.listid, count(customerlist.customerid) as numppl, list.ShortDesc from list inner join custom
customer
、list
和customerlist
(customer
和list
之间的连接表,因为它是多对多关系)
我正在尝试运行一个查询,该查询将显示所有当前列表以及当前订阅该列表的客户数(从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,您有什么想法吗?使用
左连接
代替ISNULL
以0替换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 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;
您必须使用语法
或者您可以使用:
使用合并:
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
这两个查询都将“numppl”作为布尔值返回,而不是作为COUNT()返回。如何修改此查询以将“numppl”显示为计数?是否尝试运行此查询?是-这就是我知道它将以布尔值返回的原因;)“numppl”总是返回“FALSE”-不是一个数字。对不起,它是SQL CE,不支持ISNULL。我刚刚编辑了我的答案。此SQL将每行的“numppl”显示为“FALSE”,就像Iswanto-San的回答一样。知道如何让numppl显示为一个计数吗?好的,所以我在SQLFIDLE中尝试了它,它工作了。但请记住这是SQL CE,SQL FIDLE无法准确反映它。@Teifi-好的,对不起。你是对的。我忘了。那么,您在SQLCE中遇到了什么问题呢。请告诉我您遇到的错误。我没有收到任何错误-查询工作正常,当我需要int值时只返回一个布尔值:)刚刚发现:我正在阅读它,这对我来说是新闻:)@Teifi随时欢迎您。不,很明显您使用的是SQL-CE,但这是我的错:(谢谢,我今天刚学到一些新东西。
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
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