1. 程式人生 > >sql的 case語句

sql的 case語句

在SQL的世界中CASE語句相當於if -----else  語句。

Case具有兩種格式。簡單Case函式和Case搜尋函式。

--簡單Case函式
CASE sex
WHEN '1' THEN '男'
WHEN '2' THEN '女'
ELSE '其他' END
--Case搜尋函式
CASE WHEN sex = '1' THEN '男'
WHEN sex = '2' THEN '女'
ELSE '其他' END
這兩種方式,可以實現相同的功能。

1、舉例:查詢發生時間是9月份的各時間段的數量

SELECT
COUNT(resum.id) AS number,
( CASE WHEN DATE_FORMAT(resum.happenedTime,'%H') >'8' AND DATE_FORMAT(resum.happenedTime,'%H') <= '16' THEN '8-16組'
WHEN DATE_FORMAT(resum.happenedTime,'%H') > '16' AND DATE_FORMAT(resum.happenedTime,'%H') <= '24' THEN '16-0組'
WHEN DATE_FORMAT(resum.happenedTime,'%H') > '0' AND DATE_FORMAT(resum.happenedTime,'%H') <= '8' THEN '0-8組'
END) AS projectBreakdown
FROM `naers_eventsresume` resum
INNER JOIN sys_hospital hos ON resum.hospitalId=hos.hospital_id AND hos.status=0
WHERE resum.STATUS=3 AND eventType=1
AND (resum.happenedTime BETWEEN '2018-09-01' AND CONCAT('2018-09-30',' 23:59:59'))
GROUP BY projectBreakdown;

結果如下:

 

 2、查詢9月份的事件等級I,II,III,IV的數量

SELECT eventlevel,COUNT(id) FROM `naers_events_ddzc`
WHERE `status`='3'
AND `happenedTime`>='2018-09-01 00:00:00'
AND `happenedTime`<='2018-09-30 23:59:59'
AND `type`='1'
GROUP BY eventlevel;