简体   繁体   中英

SQL - Count Null Linked Values

I have 2 tables and need to return the counts of some items grouped by category. 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

Item1 | ID1 |StatusID1 
Item2 | ID2 |StatusID2 
Item3 | ID3 |StatusID2 
Item4 | ID4 |          

Table 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. 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=''

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

You could coalesce the missing statuses before you group:

SELECT    COALESCE (status, 'Status missing'), COUNT(*)
FROM      table1
LEFT JOIN table2 ON table1.status_id = table2.status_id
GROUP BY  COALESCE (status, 'Status missing')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM