sql-按条件统计非重复值,count(distinct case when)使用

栏目: 数据库 · 发布时间: 5年前

内容简介:项目中,遇到一个统计需求,从某张表中按照条件分别统计。刚开始想到用union all的写法,太臃肿,后来使用count(distinct case when)解决此问题数据统计中,count出现最频繁最简单的用法

背景

项目中,遇到一个统计需求,从某张表中按照条件分别统计。刚开始想到用union all的写法,太臃肿,后来使用count(distinct case when)解决此问题

count

数据统计中,count出现最频繁

最简单的用法

select count(*) from table where ....

select count(distinct xx) from table where ...

但最简单的用法也有其深刻的地方,比如这里其实有3种写法,count(1)、count(*)、count(字段),它们有什么区别呢?

  • count(1) 和 count(*)

count(1)和count(*)差别不大,使用count(*)时,sql会帮你自动优化,指定到最快的字段。所以推荐使用count(*)

  • count(*) 和 count(字段)

count(*)会统计所有行数,count(字段)不会统计null值

count(case when)

条件统计,即对某个table分条件统计,比如表test_db,有一个字段user_id(可能重复), gender(man、women),需要统计man和women的人数

可以使用where分别统计

select count(distinct user_id) as man_cnt from test_db where gender = 'man'

select count(distinct user_id) as women_cnt from test_db where gender = 'women'

也可以使用按条件统计

select count(distinct case gender = 'man' then user_id end) as man_cnt

, count(distinct case gender = 'women' then user_id end) as woman_cnt

from test_db


以上所述就是小编给大家介绍的《sql-按条件统计非重复值,count(distinct case when)使用》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

计算智能导论

计算智能导论

英吉布雷切特 / 谭营 / 清华大学出版社 / 2010-6 / 59.00元

《计算智能导论(第2版)》导论性地介绍了计算智能的5 个典型范例:人工神经网络、进化计算、计算群体智能、人工免疫系统和模糊系统。它们分别是对生物神经系统、生物进化过程、社会组织的群体行为、自然免疫系统和人类思维过程的成功建模。这些范例已经得到了广泛深入的研究,人们在取得了很大的成功之后,已将研究成果广泛地应用到了众多的实际应用领域。极大提高了人们发现问题,求解问题,尤其是求解复杂科学与工程问题的能......一起来看看 《计算智能导论》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具