COUNT分组条件去重的sql统计语句示例(mysql)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了COUNT分组条件去重的sql统计语句示例(mysql)相关的知识,希望对你有一定的参考价值。
常规情况下的sql分组统计为:
select count(1) from 表 where 条件 group by 字段;
但是有时往往需要添加不同的条件已经去重的统计以上语句就不能满足需求。
解决方案为:
1.添加条件的统计方案:
COUNT(CASE WHEN 条件 THEN 1 ELSE NULL END) xxx GROUP BY 分组字段
2.添加条件并去重的统计方案:
COUNT(DISTINCT CASE WHEN 条件 THEN 去重字段 END) xxx GROUP BY 分组字段
综合示例:
SELECT dc.user_sources AS sources, COUNT(CASE WHEN dc.`count_type` IN (1,4) THEN 1 ELSE NULL END) AS djNum1, COUNT(CASE WHEN dc.`count_type` IN (2,5) THEN 1 ELSE NULL END) AS djNum2, COUNT(CASE WHEN dc.`count_type` IN (3,6) THEN 1 ELSE NULL END) AS djNum3, COUNT(DISTINCT CASE WHEN dc.`count_type` IN (1,4) THEN dc.`user_id` END) AS fwNum1, COUNT(DISTINCT CASE WHEN dc.`count_type` IN (2,5) THEN dc.`user_id` END) AS fwNum2, COUNT(DISTINCT CASE WHEN dc.`count_type` IN (3,6) THEN dc.`user_id` END) AS fwNum3, COUNT(DISTINCT CASE WHEN dc.`count_type` IN (2,5) THEN dc.`user_id` END) AS fwNumc4, COUNT(DISTINCT CASE WHEN dc.`count_type` IN (3,6) THEN dc.`user_id` END) AS fwNumc5 FROM `credit_dc_project_count` dc WHERE 1=1 AND dc.user_sources IN(‘wodong‘ , ‘qq‘ , ‘ydb_dkw‘ , ‘chh_12d‘ , ‘12d‘ , ‘jd_dkw‘ , ‘hds_dkw‘ , ‘ksd_12d‘ , ‘ttym_dkw‘ , ‘ios‘ , ‘dkwaaa‘ , ‘gzh‘ , ‘chaomi‘ , ‘mmd_12d‘ , ‘ydb_12d‘ , ‘hjsd_dkw‘ , ‘papadai‘ , ‘chd_dkw‘) GROUP BY dc.user_sources
以上是关于COUNT分组条件去重的sql统计语句示例(mysql)的主要内容,如果未能解决你的问题,请参考以下文章
MySQL 分组之后如何统计记录条数 gourp by 之后的 count()