【笔记】Mysql中使用count加条件统计

前言mysql

最近发如今处理Mysql问题时,count()函数频繁上镜,经常出如今分组统计的情景下,可是有时候并非使用group by分好组就能够直接统计了,好比说一个常见的需求,统计每一个班级男生所占的比例,这种状况通常会按照班级分组,可是分组内不但要统计班级的人数,还要统计男生的人数,也就是说统计是有条件的,以前确实没有考虑过怎样实心,后来查询了资料,总结在这里,方便往后查找使用。sql

Mysql中count()函数的通常用法是统计字段非空的记录数,因此能够利用这个特色来进行条件统计,注意这里若是字段是NULL就不会统计,可是false是会被统计到的,记住这一点,咱们接下来看看几种常见的条件统计写法。函数

测试环境
Windows 10
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 7
Server version: 5.7.21-log MySQL Community Server (GPL)
Copyright © 2000, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.
Type ‘help;’ or ‘h’ for help. Type ‘c’ to clear the current input statement.学习

准备工做
新建一个Mysql数据表a,包含id和num两个字段
mysql> create table a(id int, num int);
Query OK, 0 rows affected (0.04 sec)测试

插入测试数据,为了看count()函数的效果,咱们插入两个空数据
mysql> insert into a values (1,100),(2,200),(3,300),(4,300),(8,null),(9,null);
Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0.net

查询表a中的数据,与后面的统计作比较blog

mysql> select * from a;
id num
1 100
2 200
3 300
4 300
8 NULL
9 NULL

6 rows in set (0.09 sec)get

调用count()函数看效果,若是使用count(*)会查询出全部的记录数,但若是使用count(num)发现只有4条数据,num为NULL的记录并无统计上input

mysql> select count(*) from a;
count(*)
6

1 row in set (0.03 sec)it

mysql> select count(num) from a;
count(num)
4

1 row in set (0.04 sec)

条件统计
count()函数中使用条件表达式加or null来实现,做用就是当条件不知足时,函数变成了count(null)不会统计数量

mysql> select count(num > 200 or null) from a;
count(num > 200 or null)
2

1 row in set (0.22 sec)

count()函数中使用if表达式来实现,当条件知足是表达式的值为非空,条件不知足时表达式值为NULL;

mysql> select count(if(num > 200, 1, null)) from a;
count(if(num > 200, 1, null))
2

1 row in set (0.05 sec)

count()函数中使用case when表达式来实现,当条件知足是表达式的结果为非空,条件不知足时无结果默认为NULL;

mysql> select count(case when num > 200 then 1 end) from a;
count(case when num > 200 then 1 end)
2

1 row in set (0.07 sec)
总结
使用count()函数实现条件统计的基础是对于值为NULL的记录不计数,经常使用的有如下三种方式,假设统计num大于200的记录

select count(num > 200 or null) from a;
select count(if(num > 200, 1, null)) from a
select count(case when num > 200 then 1 end) from a
————————————————
本文仅供本身记录学习做用,版权归原做者全部,侵删
版权声明:本文为CSDN博主「AlbertS」的原创文章,遵循CC 4.0 BY-SA
原文连接:https://blog.csdn.net/alberts...

相关文章
相关标签/搜索