说我有一个学生列表,以及他们在特定班级上课的时间。我如何在SQL Server中选择那些直接参加数学课程并紧随其后的学生?示例数据如下(为清楚起见,在学生之间添加空格并通过AttendanceDateTime进行排序):
Attendance for...
[Student] [ClassAttended] [AttendanceDateTime]
--------- --------------- --------------------
John Math 2018-07-01 08:04:58.277
John Science 2018-07-01 11:00:16.201
John Composition 2018-07-01 14:03:10.112
Edward Math 2018-07-01 08:05:58.277
Edward Composition 2018-07-01 11:01:16.201
Edward Science 2018-07-01 14:02:10.112
Robert Math 2018-07-01 08:03:58.277
Robert Science 2018-07-01 11:02:16.201
Robert Composition 2018-07-01 14:01:10.112
Allen Composition 2018-07-01 08:02:58.277
Allen Math 2018-07-01 11:03:16.201
Allen Science 2018-07-01 14:00:10.112
我正在寻找的结果:
[Student]
---------
John
Robert
Allen
我已经看过How to find consecutive data in SQL和How to find consecutive rows based on the value of a column?一段时间了,我认为这个想法已经存在,但我不明白。任何朝着正确方向的指针都会受到赞赏。
答案 0 :(得分:2)
解决此问题的一种方法是在子查询中使用Lead()
函数:
SELECT DISTINCT student
FROM
(
SELECT table.*, Lead(ClassAttended) OVER (PARTITION BY Student ORDER BY AttendanceDateTime) as next_class_attended
FROM table
)sub
WHERE classAttended = 'Math' AND next_class_attended = 'Science'