Search code examples
ms-accessmultiple-columnslagdays

SQL time difference between two dates multiple conditions


I have a table (T1) which looks like that :

    ID  Date    Event
1   01/01/2010  A
1   04/01/2010  B
1   06/01/2010  A
1   09/01/2010  A
1   15/01/2010  B
2   01/02/2010  A
2   04/04/2010  A
2   01/02/2010  C
2   04/04/2010  C

I would like to calculate the difference between two dates based on "ID" and "Event" Columns. I would need a table (T2) which looks like that :

ID  Date    Date2   Ndays   Event
1   01/01/2010  06/01/2010  5   A
1   06/01/2010  09/01/2010  3   A
1   04/01/2010  15/01/2010  11  B
2   01/02/2010  04/04/2010  62  A
2   01/02/2010  04/04/2010  62  C

Solution

  • A simple Group By query will do:

    SELECT 
        Events.ID, 
        Min(Events.Date) AS Date1, 
        Max(Events.Date) AS Date2, 
        DateDiff('d',[Date1],[date2]) AS NDays, 
        Events.Event
    FROM 
        Events
    GROUP BY 
        Events.ID, 
        Events.Event;
    

    Output:

    enter image description here

    Edit:

    For more records, use a subquery:

    SELECT 
        Events.ID, 
        Events.Date AS Date1, 
        (Select Min(T.Date) 
        From Events As T 
        Where T.ID = Events.ID And T.Event = Events.Event And T.Date > Events.Date) AS Date2, DateDiff('d',[Date1],[date2]) AS NDays, 
        Events.Event
    FROM 
        Events
    GROUP BY 
        Events.ID, 
        Events.Date, 
        Events.Event
    HAVING 
        (Select Min(T.Date) 
        From Events As T 
        Where T.ID = Events.ID And T.Event = Events.Event And T.Date > Events.Date) Is Not Null
    ORDER BY 
        Events.ID, 
        Events.Event, 
        Events.Date;
    

    Output:

    enter image description here