how to get number of days between consecutive records in table?

烈酒焚心 提交于 2019-12-06 13:35:10

You can do something along these lines:

SELECT T.id, 
       T.other_col, 
       T.yourdate, 
       IFNULL(datediff(T.yourdate,(select MAX(TT.yourdate) 
                                   FROM yourtable TT 
                                   WHERE TT.yourdate < T.yourdate 
                                   AND TT.other_col = 'abc')),0)
FROM yourtable T
where other_col = 'abc';

You can see it in this fiddle

This works by calculating the difference between the current record's date (T.date) and the date that is the biggest (MAX(TT.date)) of the one's that are smaller than the current record's date ( WHERE TT.date < T.date ).

When there is no smaller date, there's the COALESCE to make it be 0, instead of null.

Edit. added coalesce to give 0 in the first line

I was going to suggest an alternative to the answer given above. If you can guarantee that the id's are sequential, you can join the table to itself to get the result you are looking for:

SELECT t1.id, t1.other_col, t1.date, DATEDIFF(t2.date,t1.date)
FROM table AS t1
LEFT_JOIN table AS t2 ON t1.id = t2.id - 1

Note that I use a LEFT JOIN here such that the first row and last rows on t1 (the main table) will be present.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!