MySQL - 使用子查询进行分组
问题描述:
我遇到了子查询和一些分组问题。子查询从整个表中选择,而不只是个别群体的......我的代码MySQL - 使用子查询进行分组
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中的特定间隔
谢谢。
答
我不认为你需要这个子查询。只要做到有条件聚集:
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
的人。
+1我打算发布一个答案,它与分组的子查询连接,另一个解决方案使用相关的子查询,但我更喜欢这个。 – Barmar
谢谢你们......我会检查一下并发布我的结果 – CameronS
是的。那样做了。真的很感谢快速回复。 – CameronS