[英]SQL - Count Null Linked Values
I have 2 tables and need to return the counts of some items grouped by category. 我有2个表格,需要返回按类别分组的某些项目的计数。 The category names are contained in another table so it looks like this and not every item has a status associated with it
类别名称包含在另一个表中,因此看起来像这样,并非每个项目都有与之关联的状态
Table 1 表格1
Item1 | ID1 |StatusID1
Item2 | ID2 |StatusID2
Item3 | ID3 |StatusID2
Item4 | ID4 |
Table 2 表2
StatusID1 | StatusA
StatusID2 | StatusB
I Basically need to see 我基本上需要看
StatusA | CountStatusA
StatusB | CountStatusB
I can get them to display when there is a status but cannot get anything when there is no status assigned. 我可以让他们在有状态的情况下显示,但在没有分配状态的情况下什么也看不到。
Thanks 谢谢
Go for a condition check where if status is null then either count it or display it as per your requirement. 进行条件检查,如果状态为null,则根据您的要求进行计数或显示。 Assuming that no status means a null value.
假设没有状态表示空值。
You can do it like this(If the status id in first table is just space ) select table2.status,count(table1.id) from table2,table1 where table1.statusid=table2.statusid group by table1.statusid union select 'No status Id',count(table1.id) from table1 where table1.statusid='' 您可以这样进行操作(如果第一个表中的状态ID仅是space),请从table2,table1中选择table2.status,count(table1.id),其中table1.statusid = table2.statusid由table1.statusid联合分组,请选择'否状态ID',来自table1的count(table1.id),其中table1.statusid =''
OR 要么
You can do it like this(If the status id in first table is null ) select table2.status,count(table1.id) from table2,table1 where table1.statusid=table2.statusid group by table1.statusid union select 'No status Id',count(table1.id) from table1 where table1.statusid is null 您可以这样进行操作(如果第一个表中的状态ID为null),则从table2,table1中选择table2.status,count(table1.id),其中table1.statusid = table2.statusid由table1.statusid联合分组,选择'无状态id',count(table1.id)来自table1,其中table1.statusid为null
You could coalesce
the missing statuses before you group: 您可以在分组之前
coalesce
丢失的状态:
SELECT COALESCE (status, 'Status missing'), COUNT(*)
FROM table1
LEFT JOIN table2 ON table1.status_id = table2.status_id
GROUP BY COALESCE (status, 'Status missing')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.