计算与日期时间上一行的天数差异
Calculate Days difference from Datetime previous row
我有一个 log_file table 是我用 Created_at 作为日期时间列创建的,我需要通过 created_at
在行之间获得天数
select id,DATE(created_at), datediff( created_at, prev_date) as diff
from (select t.*,
(select DATE(t2.created_at)
from log_file t2
where t2.id = t.id and
DATE(t2.created_at) < DATE(t.created_at)
order by t2.created_at desc
limit 1
) as prev_date
from log_file t
) t
但它在 diff
中给我 Null
id DATE(created_at) diff
2 2019-01-16 NULL
3 2019-01-19 NULL
4 2019-01-21 NULL
如果您使用的 MySQL 版本早于 8+,并且您也不想使用会话变量,那么相关子查询是一种方法。
SELECT
t1.id,
t1.created_at,
DATEDIFF(t1.created_at,
(SELECT t2.created_at FROM log_file t2
WHERE t2.created_at < t1.created_at
ORDER BY t2.created_at DESC LIMIT 1)) AS diff
FROM log_file t1;
您的方向是正确的,但是子查询中的 WHERE
子句添加的条件不正确:
where t2.id = t.id
删除它,您当前的代码甚至可以按原样工作。
我有一个 log_file table 是我用 Created_at 作为日期时间列创建的,我需要通过 created_at
在行之间获得天数select id,DATE(created_at), datediff( created_at, prev_date) as diff
from (select t.*,
(select DATE(t2.created_at)
from log_file t2
where t2.id = t.id and
DATE(t2.created_at) < DATE(t.created_at)
order by t2.created_at desc
limit 1
) as prev_date
from log_file t
) t
但它在 diff
id DATE(created_at) diff
2 2019-01-16 NULL
3 2019-01-19 NULL
4 2019-01-21 NULL
如果您使用的 MySQL 版本早于 8+,并且您也不想使用会话变量,那么相关子查询是一种方法。
SELECT
t1.id,
t1.created_at,
DATEDIFF(t1.created_at,
(SELECT t2.created_at FROM log_file t2
WHERE t2.created_at < t1.created_at
ORDER BY t2.created_at DESC LIMIT 1)) AS diff
FROM log_file t1;
您的方向是正确的,但是子查询中的 WHERE
子句添加的条件不正确:
where t2.id = t.id
删除它,您当前的代码甚至可以按原样工作。