简体   繁体   中英

How to get count of id's with missing values that are present in observations without missing values using SQL

I have a table as shown below. The table has id observations with missing values and others with actual values. What I want to get is a count of id 's only where value is missing. In this case it would be only id 4, so the count would be 1. How can I do this using SQL?

id | value
---+-------
1  | home
2  | out
3  | home
1  | 
2  |
4  |

You can do aggregation :

select id
from table t
group by id
having count(value) = 0;

Try this-

SELECT id 
FROM your_table
GROUP BY id
HAVING SUM(CASE WHEN value IS NULL OR value = '' THEN 1 ELSE 0 END) = COUNT(ID)

To get the count, you can do:

select count(distinct id)
from t
where not exists (select 1 from t t2 where t2.id = t.id and t2.value is not null);

Alternatively, you could use two levels of aggregation:

select count(*)
from (select id
      from t
      group by id
      having count(value) = 0
     ) x;

Or, if your database supports it, except :

select count(*)
from (select id from t where value is null
      except
      select id from t where value is not null
     ) x;

except removes duplicates, so distinct is not necessary.

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