我有一个包含以下数据的表格。
id start current
1 today True
2 yesterday False
1 Monday False
3 yesterday True
3 Monday False
4 today
4 Tuesday
5 Wednesday True
6 Friday
6 Monday
7 Sunday True
7 Tuesday
我想检查当前列中包含所有空值的 id 数量并打印该计数。
我想使用按 id 分组并选择当前为空但未给出适当计数的 id。仅当特定 id 的所有行都包含当前为 null 时,我才想计数。
试试这个: http://sqlfiddle.com/#!9/31f6e/12
select count(distinct start)
from
(
select start,max(case when current is not null then 1 else 0 end) mt
from data
group by start)a where mt=0
- 首先,找到
MAX(current)
为 NULL 的所有 id。 - 然后,只需将它们数出来。
尝试以下查询(将在 MySQL 中工作(:
SELECT COUNT(DISTINCT IF(derived_t.max_current IS NULL,
derived_t.id,
NULL)) AS ids_with_all_null
(
SELECT id, MAX(current) as max_current
FROM your_table
GROUP BY id
) AS derived_t
你可以为此使用 exist-clause。"查找没有除NULL
以外的值为current
的行的单个id
的计数">
select count(distinct d.id)
from data d
where not exists (
select *
from data d2
where d2.id=d.id and d2.current is not null
)
请参阅 SQLFiddle