- 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,而當有一個成立之后,后面的就不執行了。
- 將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;
參考文章 :