我在mysql数据库的webinar_timing表中有以下数据
start_time和end_time的类型为datetime
id | webinar_id | start_time | end_time ------------------------------------------------------------------- 1 | 5 | 3/18/2015 6:00:00 PM | 3/18/2015 7:00:00 PM 2 | 5 | 3/19/2015 6:00:00 PM | 3/19/2015 7:00:00 PM 3 | 5 | 3/20/2015 6:00:00 PM | 3/20/2015 7:00:00 PM 4 | 5 | 3/21/2015 6:00:00 PM | 3/21/2015 7:00:00 PM 5 | 5 | 3/22/2015 6:00:00 PM | 3/22/2015 7:00:00 PM 6 | 11 | 3/20/2015 8:00:00 PM | 3/20/2015 9:00:00 PM 7 | 11 | 3/21/2015 8:00:00 PM | 3/21/2015 9:00:00 PM 8 | 11 | 3/22/2015 8:00:00 PM | 3/22/2015 9:00:00 PM 9 | 22 | 3/25/2015 8:00:00 PM | 3/25/2015 9:00:00 PM 10 | 22 | 3/27/2015 8:00:00 PM | 3/27/2015 9:00:00 PM 11 | 22 | 3/29/2015 8:00:00 PM | 3/27/2015 9:00:00 PM
基本上,对于每个网络研讨会,我都希望完成或剩余的课程总数和课程数量以及NEXT即将开课的课程
Egs:当我运行此查询时,请在2015年3月21日下午4:00说 - 这是我期待的结果
webinar_id | total | Classes Completed | Next Class ---------------------------------------------------------- 5 | 5 | 3 | 3/21/2015 6:00:00 PM 11 | 3 | 1 | 3/21/2015 8:00:00 PM 22 | 3 | 0 | 3/25/2015 8:00:00 PM
OR
webinar_id | total | Classes Remaining | Next Class ---------------------------------------------------------- 5 | 5 | 2 | 3/21/2015 6:00:00 PM 11 | 3 | 2 | 3/21/2015 8:00:00 PM 22 | 3 | 3 | 3/25/2015 8:00:00 PM
任何帮助将不胜感激 提前致谢
答案 0 :(得分:1)
只需使用SUM(IF(...))
select webinar_id, count(*) AS total,
SUM(IF(end_time<NOW(), 1, 0)) AS completed,
SUM(IF(start_time>=NOW(), 1, 0)) AS remaining
from webinar_times
group by webinar_id;
你必须弄清楚你是在看start_time还是end_time,以及如何处理equals和那些小细节......
答案 1 :(得分:0)
SELECT COUNT(*), W.webinar_id, X.COMPLETED, Y.[NOT COMPLETE]
FROM #Webinars W
JOIN (SELECT COUNT(*) AS 'COMPLETED', webinar_id
FROM #Webinars
WHERE end_tim <= '3/18/2015 7:00:00'
GROUP BY webinar_id) X
ON X.webinar_id = W.webinar_id
JOIN (SELECT COUNT(*) AS 'NOT COMPLETE', webinar_id
FROM #Webinars
WHERE end_tim > '3/18/2015 7:00:00'
GROUP BY webinar_id) Y
ON Y.webinar_id = W.webinar_id
GROUP BY W.webinar_id, X.COMPLETED, Y.[NOT COMPLETE]