1

我有一张表,其中包含上课学生的到达和离开时间。给定这样的数据:

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; 

提前感谢任何可以帮助我解决此问题的人。

4

1 回答 1

0

使用correlated sub-queries您可以创建虚拟表(与 a 不同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  

该报告显示在每个活动时间仍有多少学生“在这里”。

希望这对您有用。

于 2013-03-28T23:45:19.207 回答