优化这段sql SELECT (CASE WHEN DATE_FORMAT( `start_time`, '%H:%i:%S' ) > '00:00:00' and DATE_FORMAT( `start_time`, '%H:%i:%S' ) <= '03:59:59' THEN '00:00-03:59' WHEN DATE_FORMAT( `start_time`, '%H:%i:%S' ) > '04:00:00' and DATE_FORMAT( `start_time`, '%H:%i:%S' ) <= '07:59:59' THEN '04:00-07:59' WHEN DATE_FORMAT( `start_time`, '%H:%i:%S' ) > '08:00:00' and DATE_FORMAT( `start_time`, '%H:%i:%S' ) <= '11:59:59' THEN '08:00-11:59' WHEN DATE_FORMAT( `start_time`, '%H:%i:%S' ) > '12:00:00' and DATE_FORMAT( `start_time`, '%H:%i:%S' ) <= '15:59:59' THEN '12:00-15:59' WHEN DATE_FORMAT( `start_time`, '%H:%i:%S' ) > '16:00:00' and DATE_FORMAT( `start_time`, '%H:%i:%S' ) <= '19:59:59' THEN '16:00-19:59' WHEN DATE_FORMAT( `start_time`, '%H:%i:%S' ) > '20:00:00' and DATE_FORMAT( `start_time`, '%H:%i:%S' ) <= '23:59:59' THEN '20:00-23:59' ELSE '' END) AS timeInterval, IFNULL( SUM( `dual_time` ), 0 ) AS totalTime, IFNULL( COUNT(1), 0 ) AS totalCall, IFNULL( SUM( CASE WHEN `local_action` = '主叫' THEN 1 ELSE 0 END ), 0 ) AS active, IFNULL( SUM( CASE WHEN `local_action` = '被叫' THEN 1 ELSE 0 END ), 0 ) AS passive FROM `dwd_t_call_record` WHERE `person_no` = '653129200105072624' GROUP BY HOUR ( `start_time` ) DIV 4
时间: 2024-02-21 17:59:14 浏览: 160
SQL 的 SELECT 语句优化
可以使用 MySQL 的 `CASE WHEN` 语句来简化这段 SQL 语句,同时避免重复的日期格式化操作。简化后的 SQL 语句如下:
```
SELECT
CONCAT(HOUR(`start_time`) DIV 4 * 4, ':00-', HOUR(`start_time`) DIV 4 * 4 + 3, ':59') AS timeInterval,
IFNULL(SUM(`dual_time`), 0) AS totalTime,
IFNULL(COUNT(1), 0) AS totalCall,
IFNULL(SUM(`local_action` = '主叫'), 0) AS active,
IFNULL(SUM(`local_action` = '被叫'), 0) AS passive
FROM
`dwd_t_call_record`
WHERE
`person_no` = '653129200105072624'
GROUP BY
HOUR(`start_time`) DIV 4
```
这个 SQL 语句使用了 `CONCAT` 函数来生成时间区间,使用了 `SUM` 函数的布尔表达式参数来计算主叫和被叫的数量。同时,将日期格式化操作转化为了整数运算,避免了多次重复的格式化操作。
阅读全文