SQL的count函数怎么应对多列计算的情况

您所在的位置:网站首页 数据库计数函数count语句 SQL的count函数怎么应对多列计算的情况

SQL的count函数怎么应对多列计算的情况

2024-06-29 09:38| 来源: 网络整理| 查看: 265

开门见山:

count(*) : 行数有多少就是多少,包括nullcount(col) : col的行数,不包括null值count(distinct col) : 去重的col行数,不包括null值count(distinct col1, col2) : 去重的(col1 AND col2)行数,不包括null值

count(distinct 多列) 实际是一个并集的概念,也可以用这句命令来理解:SUM(col1 IS NOT NULL AND col2 IS NOT NULL)

举个栗子:

假使现在有个test表如下:

test表共有13条记录,是关于2022年11月份的新生儿的性别和出生日期。

gender是新出生儿童的性别,有2个空值

birth_date是新生儿的具体出生日期,有4个空值

 跑以下代码:

select count(*), # = 13 count(gender), # = 11 count(birth_date), # = 9 count(distinct gender), # = 2 count(distinct birth_date), # = 9 count(distinct gender, birth_date), # = 7 count(distinct gender, date(birth_date)) # = 6 from test

count(*):一共有13条记录,包括了null值

count(gender):gender字段里有2个空值(13-2)

count(birth_date):birth_date字段里有4个空值(13-4)

count(distinct gender):gender只有两个属性,F和M,不管空值

count(distinct birth_date):birth_date里面有9个日期,分别为2022/11/1 10:23;2022/11/1 21:09;2022/11/8 12:11;2022/11/8 5:01;2022/11/8 10:58;2022/11/9 2:46;2022/11/10 3:00;2022/11/13 17:23;2022/11/15 19:51,不管空值

count(distinct gender, birth_date):要同时满足gender和birth_date互不为空的值的个数,具体如下,共7条记录

 

count(distinct gender, date(birth_date)): 要同时满足distinct,以及字段gender和birth_date互不为空的两个条件,这里请注意看id=5的记录被剔除了,是因为和id=4的gender=F记录相同而被去重了。具体如下,共有6条记录

看到这里你真的很棒,希望我这篇笔记帮你把count都搞懂了哈哈~~~~~~



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3