我有一张表,其中包含上课学生的到达和离开时间。给定这样的数据:
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;
提前感谢任何可以帮助我解决此问题的人。