MySQL高级函数case的使用技巧----与sum结合实现分段统计

  • case 函数 
1 CASE 
2     WHEN condition1 THEN result1
3     WHEN condition2 THEN result2
4    ...
5     WHEN conditionN THEN resultN
6     ELSE result
7 END

CASE 表示函数开始,END 表示函数结束。

如果 condition1 成立,则返回 result1, 如果 condition2 成立,则返回 result2,

当全部不成立则返回 result,而当有一个成立之后,后面的就不执行了。

  •   sumcase结合使用,可以实现分段统计
1 select
2      sum(case when b.device_id is not null then 1 else 0 end)  hasDeviceCount,
3      sum(case when b.detector_id is not null then 1 else 0 end) hasDetectorCount,
4      sum(case when b.status = 1 then 1 else 0 end)  hasOccupiedCount
5  from berth_info b;

 

参考文章 :

https://blog.csdn.net/beidaol/article/details/84344759

https://www.cnblogs.com/clphp/p/6256207.html

posted @ 2019-03-19 19:09  波比爱吃肉  阅读(1362)  评论(0编辑  收藏  举报