Say I have a list of students and the time their attendance was taken in specific class types. How would I SELECT in SQL Server those students who attended a Math class directly followed by Science? Sample data as follows (adding spaces between students and sequencing by AttendanceDateTime for clarity):
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
Results I am looking for:
[Student]
---------
John
Robert
Allen
I have looked at both How to find consecutive data in SQL and How to find consecutive rows based on the value of a column? for a while now and I think the idea is there but I'm not getting it. Any pointer in the right direction is much appreciated.
One way to solve this is with the Lead()
function in a subquery:
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'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.