Home Forums SQL Server 2008 T-SQL (SS2K8) Need help identifying dates of an occurance after a specific date RE: Need help identifying dates of an occurance after a specific date

  • This could help point you in correct direction, regardless of the number of accidents

    CREATE TABLE #tblDrivers (DriverID Int, AccidentDate date)

    INSERT INTO #tblDrivers(DriverID,AccidentDate)

    VALUES (1,'03/01/2012'),

    (1,'05/06/2015'),

    (2,'08/05/2013'),

    (3,'12/01/2011'),

    (4,'06/22/2005'),

    (4,'04/01/2008'),

    (4,'11/21/2010')

    GO

    CREATE TABLE #tblDrivingSchool (DriverID Int, ClassDate date)

    INSERT INTO #tblDrivingSchool (DriverID,ClassDate)

    values

    (1,'03/15/2012'),

    (3,'12/18/2011'),

    (4,'07/10/2005')

    ;

    With

    Driver_Accident_History as

    ( Select

    a.DriverID

    ,a.AccidentDate

    ,ROW_NUMBER() over (partition by a.DriverID order by a.AccidentDate) as Accident_Number

    from #tblDrivers a

    group by

    a.DriverID

    ,a.AccidentDate)

    Select

    a.DriverID

    ,a.Accident_Number

    ,a.AccidentDate

    ,count(b.ClassDate) as Driving_classes_Attended_Prior_To_Accident

    ,max(b.ClassDate) as Last_Driving_classes_Prior_To_Accident

    ,count(c.ClassDate) as Driving_classes_Attended_After_Accident

    ,min(c.ClassDate) as First_Driving_classes_After_Accident

    from Driver_Accident_History a

    left join #tblDrivingSchool b on a.DriverID = b.DriverID and b.ClassDate <= a.AccidentDate

    left join #tblDrivingSchool c on a.DriverID = c.DriverID and c.ClassDate > a.AccidentDate

    Group by

    a.DriverID

    ,a.Accident_Number

    ,a.AccidentDate

    Drop table #tblDrivers,#tblDrivingSchool