简体   繁体   中英

Using lag to access previous row value in mysql

I have a datetime columns, that are fromDate and toDate .

I am trying to figure out if the interval is continuos.

This is how my table looks this:

在此处输入图片说明

I would like to get the following results with 3 intervals:

fromDate            | toDate
2020-05-23 08:00:00 | 2020-05-23 09:15:00
2020-05-23 11:00:00 | 2020-05-23 12:00:00
2020-05-23 15:00:00 | 2020-05-23 15:30:00

Any idea how to do this?

This is a gaps-and-islands problem, where you want to group together "adjacent" rows.

Here is one option using lag() to recover the todate on the previous row, and then a window sum() to identify the islands. The final step is to aggregate each island:

select min(fromdate) fromdate, max(todate) todate
from (
    select t.*, 
        sum(case when fromdate = lag_todate then 0 else 1 end) over(order by fromdate) grp
    from (
        select t.*, lag(todate) over(order by fromdate) lag_todate
        from mytable t
    ) t
) t
group by grp

Note: since you are running MySQL, we can simplify the expression in the window sum a little. This is shorter, and should work just fine:

sum(1 - fromdate <=> lag_todate) over(order by fromdate) grp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM