我的目标是GROUP (eid) SORT BY dayatime()
,选择每组中的前2次,计算日差。
我知道这个想法,但是我怎样才能将它转化为真正的 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 |
最佳答案
本质上,您需要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;
关于mysql - 如何计算相同事件的日差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35122621/