简体   繁体   English

MySQL-使用子查询分组

[英]MySQL - Grouping with subquery

I am having trouble with a subquery and some grouping. 我在使用子查询和某些分组时遇到麻烦。 The subquery is selecting from the whole table instead of just the individual groups...my code 子查询从整个表中进行选择,而不仅仅是单个组...我的代码

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

My goal is to have that subquery just return the number of records where that TIMEDIFF result is less than 40 within that particular interval 我的目标是让子查询仅返回在特定间隔内TIMEDIFF结果小于40的记录数

Thanks. 谢谢。

I don't think you need a subquery for this. 我认为您不需要为此的子查询。 Just do conditional aggregation: 只需执行条件聚合:

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;

You would use the subquery to get a total over all record, not the ones affected by the where clause or the group by . 您将使用子查询获取所有记录的总数,而不是受where子句或group by影响的记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM