0

假设我有一份学生名单,以及他们在特定班级类型中的出勤时间。我将如何在 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

我已经查看了如何在 SQL 中查找连续数据如何根据列的值查找连续行?有一段时间了,我认为这个想法就在那里,但我不明白。任何指向正确方向的指针都非常感谢。

4

1 回答 1

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'
于 2018-07-31T16:56:38.210 回答