2013-03-28 46 views
1

我有一張表格,其中包含出席課程的學生的到達和離開時間。給定類似這樣的數據: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; 

謝謝提前給任何能幫助我解決問題的人。

+0

您將需要使用聚合函數,查看group by和count(distinct student_id)等。[閱讀本文](http://dev.mysql.com/doc/refman/5.0/zh-cn/group-by -functions.html) – mconlin

+0

感謝您的鏈接@mconlin :) – lifeform

回答

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 

報告顯示在每個活動時間裏仍有多少學生在這裏。

希望這對你有用。

+0

這將做到!我可以使用php來遍歷結果集並優化數據。非常感謝你的幫助,@majorbanzai。 – lifeform