MySQL - 使用子查询进行分组

时间:2013-07-20 02:21:29

标签: mysql subquery

我遇到子查询和一些分组的问题。子查询是从整个表中选择的,而不仅仅是单个组...我的代码

SELECT SEC_TO_TIME(TIME_TO_SEC(call_start) - TIME_TO_SEC(call_start)%(30*60)) AS intervals, 
       COUNT(*) AS OFFERED, 
       SUM(agent_duration) AS AGENT_SUM, 
       SUM(TIME_TO_SEC(TIMEDIFF(dequeue_time, enqueue_time))) AS ANS_TIME_SUM, 
       COUNT(DISTINCT agent_username) AS UNIQUE_AGENTS, 
       (SELECT COUNT(*) FROM call_detail
        WHERE TIME_TO_SEC(TIMEDIFF(dequeue_time, enqueue_time)) < 40) AS SLA, 
       SUM(queue_duration) AS TOTAL_QUEUE_TIME 
FROM call_detail
WHERE DATE(call_start) = CURDATE()
GROUP BY intervals

我的目标是让该子查询返回该特定时间间隔内TIMEDIFF结果小于40的记录数

感谢。

1 个答案:

答案 0 :(得分:1)

我认为你不需要子查询。只做条件聚合:

SELECT SEC_TO_TIME(TIME_TO_SEC(call_start) - TIME_TO_SEC(call_start)%(30*60)) AS intervals, 
       COUNT(*) AS OFFERED, 
       SUM(agent_duration) AS AGENT_SUM, 
       SUM(TIME_TO_SEC(TIMEDIFF(dequeue_time, enqueue_time))) AS ANS_TIME_SUM, 
       COUNT(DISTINCT agent_username) AS UNIQUE_AGENTS, 
       sum(case when TIME_TO_SEC(TIMEDIFF(dequeue_time, enqueue_time)) < 40 then 1 else 0 end) as SLA,
       SUM(queue_duration) AS TOTAL_QUEUE_TIME 
FROM call_detail
WHERE DATE(call_start) = CURDATE()
GROUP BY intervals;

您可以使用子查询来获取所有记录的总计,而不是受where子句或group by影响的记录。