简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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