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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM