COUNT分组条件去重的sql统计语句示例(mysql)

发布时间2018/11/30 15:55:56

下载次数 0 次 访问量223 次

免开发-应用中心上线啦,专注提供优质插件源码和产品应用!

常规情况下的sql分组统计为:

 select count(1) fromwhere 条件 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
复制代码

 

网友评论

发表评论

欢迎评论哦!