码迷,mamicode.com
首页 > 数据库 > 详细

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

时间:2018-11-27 19:40:13      阅读:450      评论:0      收藏:0      [点我收藏+]

标签:case   project   mys   else   color   rom   方案   语句   ase   

常规情况下的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

 

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

标签:case   project   mys   else   color   rom   方案   语句   ase   

原文地址:https://www.cnblogs.com/007sx/p/10028025.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!