2016-02-01 41 views
0

我的目標是GROUP (eid) sort by dayatime() pick the first 2 times in each group, cal the day difference.如何計算同一事件

一天deffirence我知道的想法,但我怎麼可能轉化爲真正的MySQL查詢語法?

mysql> select * from events; 
+------+------------+ 
| eid | dt   | 
+------+------------+ 
| 1 | 2013-01-01 | -> 3 
| 1 | 2013-01-04 | -> 1 
| 1 | 2013-01-05 | 
| 2 | 2013-04-01 | -> 7 
| 2 | 2013-04-08 | 
+------+------------+ 
5 rows in set (0.00 sec) 


GOAL: query that gives this result: 
+------+------------+-----------------+ 
| eid | dt   | days_until_next | 
+------+------------+-----------------+ 
| 1 | 2013-01-01 |    3 | 
| 1 | 2013-01-04 |    1 | 
| 2 | 2013-04-01 |    7 | 

回答

1

本質上,你想要lead()的功能,但MySQL不支持這個功能。相反,您可以使用相關的子查詢:

select e.eid, e.dt, datediff(next_dt, dt) as days_until_next 
from (select e.*, 
      (select dt 
       from events e2 
       where e2.eid = e.eid and e2.dt > e.dt 
      ) as next_dt 
     from events e 
    ) e 
where next_dt is not null;