I am currently working with SQL server 2008. I have multiple records that have students enrolled in the same course but some records have the same start date and null value or an actual date for the end date. I am trying to get the records with the null value if the start date is the same for the same student. The data in the system also contains records with a start and end date but I am intending to keep those records. I have tried the query below but it is not giving me back any results. Is there a way to accomplish this? Any help would be appreciated.
SELECT DISTINCT
t1.*
FROM Enrolled_students t1
JOIN Enrolled_students t2
ON t1.studentid = t2.studentid
AND t1.program_enrolled = t2.program_enrolled
AND t1.startdate = t2.stardate
AND t1.enddate <> t2.enddate
DATA
StudentID program StartDate enddate_Date
267342 Science 2016-09-19 00:00:00.000 NULL
267342 science 2016-09-19 00:00:00.000 2017-01-17 00:00:00.000
435359 math 2017-05-18 00:00:00.000 2017-08-29 00:00:00.000
290332 Lab 2014-02-11 00:00:00.000 NULL
RESULTS
StudentID program startDate end_Date
267342 Science 2016-09-19 00:00:00.000 NULL
435359 math 2017-05-18 00:00:00.000 2017-08-29 00:00:00.000
290332 Lab 2014-02-11 00:00:00.000 NULL
答案 0 :(得分:4)
Run the below SQL. this will return you the Student records with End Date which has another entry in the same table for the same student+course+start date combination with NULL in the end date
SELECT
*
FROM Enrolled_students
WHERE enddate_Date IS NOT NULL
AND EXISTS
(
SELECT
1
FROM Enrolled_students ES
WHERE ES.StudentID = Enrolled_students.StudentID
AND ES.Program = Enrolled_students.Program
AND ES.StartDate = Enrolled_students.StartDate
AND ES.enddate_Date IS NULL
)
答案 1 :(得分:1)
You can try this.
SELECT * FROM Enrolled_students E1
WHERE NOT EXISTS
( SELECT * FROM Enrolled_students E2
WHERE E1.StudentID = E2.StudentID
AND E1.enddate_Date IS NOT NULL
AND E2.enddate_Date IS NULL )
Result:
StudentID program StartDate enddate_Date
----------- -------------------- ----------------------- -----------------------
267342 Science 2016-09-19 00:00:00.000 NULL
435359 math 2017-05-18 00:00:00.000 2017-08-29 00:00:00.000
290332 Lab 2014-02-11 00:00:00.000 NULL