MySQL中count()的条件统计方式

前几天做笔试题时遇到一个问题,如下:
一个info表内容如下:

date result
2019-10-12 high
2019-10-12 low
2019-10-12 high
2019-10-16 low
2019-10-16 low
2019-10-16 high

请写出相应的SQL语句,以得出以下的查询结果:

date low high
2019-10-12 1 2
2019-10-16 2 1

当时没做出来,后面查找资料后得出了答案:

select
	date,
	count(result='low' or null) as low,
	count(result='high' or null) as high 
from info group by date;

如何理解其中的"or null"呢?
我是这样子理解的,如果result不等于要统计的值的时候,就把它当做null值来计算,即count(null),因为count()是不会把null计算进去的。

除此之外,其实还有其他的条件统计方式,我总结如下:

1.使用if表达式

select
	date,
	count(if(result='low',1,null)) as low,
	count(if(result='high',1,null)) as high
from info group by date;

2.使用case when表达式

select
	date,
	count(case when result='low' then 1 end) as low,
	count(case when result='high' then 1 end) as high
from info group by date;

猜你喜欢

转载自blog.csdn.net/weixin_38418951/article/details/102594494