在Mysql中,为什么sum具有count的功能?
时间:2011-08-11
来源:互联网
temp字段存储的是-5到50的数字,目的是求temp在某个区间的计数,但是用count的结果每一列都是365或366,但用sum却能得到结果,请问这是为什么?
下面是这段查询语名,请大家指教:
select left(`date`,4),
sum( temp<5) as `5`,
sum(temp>=5 && temp<10) as `10`,
sum(temp>=10 && temp<15) as `15`,
sum(temp>=15 && temp<20) as `20`,
sum(temp>=20 && temp<30) as `30`,
sum(temp>=30 && temp<40) as `40`,
sum(temp>=40 && temp<50) as `50`
from beibei
group by left(`date`,4);
下面是这段查询语名,请大家指教:
select left(`date`,4),
sum( temp<5) as `5`,
sum(temp>=5 && temp<10) as `10`,
sum(temp>=10 && temp<15) as `15`,
sum(temp>=15 && temp<20) as `20`,
sum(temp>=20 && temp<30) as `30`,
sum(temp>=30 && temp<40) as `40`,
sum(temp>=40 && temp<50) as `50`
from beibei
group by left(`date`,4);
作者: lishnqing 发布时间: 2011-08-11
sum( temp<5)=>
sum(if(temp<5,1,0))
select *,temp<5 from beibei 看看结果,满足temp<5时为1,否则为0
sum(if(temp<5,1,0))
select *,temp<5 from beibei 看看结果,满足temp<5时为1,否则为0
作者: WWWWA 发布时间: 2011-08-11
你这句看上去应该是正确的,但我不明白为什么用count不行。
作者: lishnqing 发布时间: 2011-08-11
基于如下结论:
1. sum(1) 和 count(1) 是一样的
2. 条件表达式的结果是 1 或 0
3. sum(0) 和 count(null) 是一样的
所以,你要使用 count 的话,可以如下改变(注:没有测试,所以你要自己调试了):SQL code
1. sum(1) 和 count(1) 是一样的
2. 条件表达式的结果是 1 或 0
3. sum(0) 和 count(null) 是一样的
所以,你要使用 count 的话,可以如下改变(注:没有测试,所以你要自己调试了):SQL code
select left(`date`,4), count(if(temp<5, 1, null)) as `5`, count(if(temp>=5 && temp<10 , 1, null)) as `10`, count(if(temp>=10 && temp<15, 1, null)) as `15`, count(if(temp>=15 && temp<20, 1, null)) as `20`, count(if(temp>=20 && temp<30, 1, null)) as `30`, count(if(temp>=30 && temp<40, 1, null)) as `40`, count(if(temp>=40 && temp<50, 1, null)) as `50` from beibei group by left(`date`,4);
作者: nicenight 发布时间: 2011-08-11
引用 2 楼 lishnqing 的回复:
你这句看上去应该是正确的,但我不明白为什么用count不行。
你这句看上去应该是正确的,但我不明白为什么用count不行。
count得到的是所有行数,当然不正确
sum(if(temp<5,1,0))
满足条件的结果为1 ,再求和
作者: wwwwb 发布时间: 2011-08-11
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28