Mysql group by 后面怎么加判断条件?

有下面的 SQL 语句:

select count(*) from text_meta_ingest group by bool(clip_url_hash)

我希望可以统计 clip_url_hash 为:

  • null
  • ''(空字符)
  • 有实际值(长度大于 0)

这三种情况的 count,我应该怎么写?

阅读 4.6k
2 个回答

用 case when 一劳永逸哦

select 
    d.checks, count(d.checks)
from (select (
    case clip_url_hash
    when '' then '空字符串'
    when null then 'NULL'
    else '正常的' end
) as checks from text_meta_ingest) as d
group by d.checks;

我测试的
image.png

就按你说的写啊,比如

select count(*) from text_meta_ingest group by IF(clip_url_hash is NULL, null, IF(clip_url_hash = '', '', 1));

嗯,你说的对...

select sum(if(core_chemical_code is null, 1, 0)) as totalNull, sum(if(core_chemical_code = '', 1, 0)) as totalEmpty, count(*) as total from text_meta_ingest

非空的行是 total - totalNull - totalEmpty

推荐问题
宣传栏