MySQL-case函数-与sum结合实现分段统计

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,而当有一个成立之后,后面的就不执行了。

举例:https://jingyan.baidu.com/article/fd8044facadad75030137a52.html

 

sum与case结合使用,可以实现分段统计

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://www.cnblogs.com/jvjs/p/10560639.html

posted @ 2020-07-13 14:44  ShulinW  阅读(295)  评论(0)    收藏  举报