我有一張表格,其中包含出席課程的學生的到達和離開時間。給定類似這樣的數據:MySQL查找按時間細分的出席學生人數
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語句到目前爲止我越來越某種方式對答案,但我不能完全得到它的工作:
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;
謝謝提前給任何能幫助我解決問題的人。
您將需要使用聚合函數,查看group by和count(distinct student_id)等。[閱讀本文](http://dev.mysql.com/doc/refman/5.0/zh-cn/group-by -functions.html) – mconlin
感謝您的鏈接@mconlin :) – lifeform