
如何在使用 group by 后对 mysql 结果进行条件判断?
在 mysql 中使用 group by 对结果分组时,我们有时需要进一步对分组后的数据进行条件判断。例如,我们需要统计列 clip_url_hash 的三种情况:null、''(空字符串)和有实际值。
为了实现这个目标,我们可以利用 case when 语句。
select
d.checks,
count(d.checks)
from (
select
case
when clip_url_hash = '' then '空字符串'
when clip_url_hash is null then 'null'
else '正常的'
end as checks
from text_meta_ingest
) as d
group by
d.checks;解释:
- 内层查询使用 case when 语句将 clip_url_hash 值映射为三个不同的检查结果:空字符串、null 和正常值。
- 外层查询使用 count() 函数对 checks 列进行计数。
- group by 子句根据 checks 值对结果进行分组。
结果:
checks count 空字符串 xxx NULL yyy 正常的 zzz










