SQL两个日期的时间差多个条件

SQL time difference between two dates multiple conditions

我有一个看起来像这样的 table (T1) :

    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

我想根据 "ID" 和 "Event" 列计算两个日期之间的差异。我需要一个看起来像这样的 table (T2) :

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

一个简单的 Group By 查询即可:

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;

输出:

编辑:

要获取更多记录,请使用子查询:

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;

输出:

使用自连接和聚合:

SELECT t.ID, t.Date, 
  MIN(tt.Date) AS Date2, 
  DATEDIFF('d', t.Date, Date2) AS NDays,
  t.Event
FROM tablename t INNER JOIN tablename tt
ON tt.ID = t.ID AND tt.Event = t.Event AND t.Date < tt.Date
GROUP BY t.ID, t.Date, t.Event
ORDER BY t.ID, t.Event, t.Date

结果:

ID  Date        Date2       NDays   Event
1   1/1/2010    6/1/2010    5       A
1   6/1/2010    9/1/2010    3       A
1   4/1/2010    15/1/2010   11      B
2   1/2/2010    4/4/2010    62      A
2   1/2/2010    4/4/2010    62      C