我有一张桌子,其中包含参加课程的学生的到达和离开时间。给出类似这样的数据:
CREATE TABLE `attendance` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`class_id` int(11) DEFAULT NULL,
`student_id` int(11) NOT NULL DEFAULT '0',
`arrival` datetime DEFAULT NULL,
`departure` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `attendance` (`id`, `class_id`, `student_id`, `arrival`, `departure`)
VALUES
(1,1,1,'2013-01-01 16:00:00','2013-01-01 17:00:00'),
(2,1,2,'2013-01-01 16:00:00','2013-01-01 18:00:00'),
(3,1,3,'2013-01-01 17:00:00','2013-01-01 19:00:00'),
(4,1,4,'2013-01-01 17:00:00','2013-01-01 19:00:00'),
(5,1,5,'2013-01-01 17:30:00','2013-01-01 18:30:00');
我试图在几分钟内得出时间细分,以及该时间段内有多少学生在场。上述数据的结果如下:
Time Students
60 2 (the first hour from 16:00 to 17:00 has students 1 & 2)
30 3 (the next 30 minutes from 17:00 to 17:30 has students 2, 3 & 4)
30 4 (etc...)
30 3
30 2
我到目前为止的选择声明正在寻找答案,但我无法让它发挥作用:
SELECT a.id, a.arrival, b.id, LEAST(a.departure,b.departure) AS departure,
TIMEDIFF((LEAST(a.departure,b.departure)),(a.arrival)) AS subtime
FROM attendance a
JOIN attendance b ON (a.id <> b.id and a.class_id=b.class_id
and a.arrival >= b.arrival and a.arrival < b.departure)
WHERE a.class_id=1
ORDER BY a.arrival, departure, b.id;
提前感谢任何可以帮助我做到这一点的人。
答案 0 :(得分:0)
使用correlated sub-queries
您可以创建虚拟表(与temporary table
不同,但有点相同)。然后,您可以查询这些虚拟表,就像它们确实存在一样。
select clocks.clock, count( att.student_id ) as numStudents
from
(
( select arrival as clock from attendance )
union distinct
( select departure as clock from attendance )
)
as clocks
left outer join attendance att on att.arrival <= clocks.clock and clocks.clock < att.departure
group by clocks.clock
order by 1,2
;
几乎你在寻找什么。这不是按经过时间分组,而是使用实际的“事件”时间戳(到达和离开),并为您提供有用的报告。
clock numStudents
------------------- -----------
2013-01-01 16:00:00 2
2013-01-01 17:00:00 3
2013-01-01 17:30:00 4
2013-01-01 18:00:00 3
2013-01-01 18:30:00 2
2013-01-01 19:00:00 0
报告显示每个活动时有多少学生还在这里。
希望这对你有用。