[英]Selecting distinct count in a group with only null values for a specific column
I have 2 columns like this - id and val. 我有这样两列-id和val。
I require such distinct id's where corresponding to each id there is a null value present. 我需要这样的独特ID,其中每个ID对应一个null值。 Is it plausible to use "group by" by id and then use "having" clause where null is there? 使用id的“ group by”,然后在存在null的地方使用“ having”子句是否合理?
I would use NOT EXISTS
: 我会使用NOT EXISTS
:
SELECT COUNT(DISTINCT id)
FROM table t
WHERE NOT EXISTS (SELECT 1 FROM table t1 WHERE t1.id = t.id AND t1.val IS NOT NULL);
Other option uses the GROUP BY
: 其他选项使用GROUP BY
:
SELECT COUNT(id)
FROM table t
GROUP BY id
HAVING SUM(CASE WHEN val IS NOT NULL THEN 1 ELSE 0 END) = 0;
To get ids that have a NULL
value, I would be inclined to start with this: 为了获得具有NULL
值的id,我倾向于从这个开始:
select id
from t
group by id
having count(*) <> count(val);
This structure allows you to check for other values, such as a non- NULL
value. 此结构允许您检查其他值,例如非NULL
值。
The simplest method to get the distinct ids with NULL
values is: 获取具有NULL
值的不同ID的最简单方法是:
select distinct id
from t
where val is null;
If you only want the count: 如果只想计数:
select count(distinct id)
from t
where val is null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.