mysql - 如何计算相同事​​件的日差

标签 mysql

我的目标是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/

相关文章:

mysql - 我们应该在表中进行哪些更改

MySQL-SELECT * INTO OUTFILE LOCAL?

javascript - 嵌套包含在sequelize中?

mysql - 如果(作为一个组)满足条件,则获取表中的每一行

mysql - 统计MySQL中的数据

mysql - 如何根据用户数量获取客户数据?

mysql - MYSQL中如何拼接一个组中前N条记录的查询结果

mysql - codeception:运行多个 sql 转储文件

sql - 如何在 MySQL 中执行 FULL OUTER JOIN?

mysql - SQL : What is the default Order By of queries?