Search code examples
sqlpostgresqldatetimewindow-functionsgaps-and-islands

Calculate difference between current row and next available date value in SQL


I have get difference between the current Issue Reset and next stop time in Postgres SQL. I am not able to understand, how can i get this done using window functions. I tried NEXT_VALUE and FIRST_VALUE, but i am seeing examples for moving aggregates. I need a single query to get this.

I need to achieve difference between '22/08/2020 11:29:00' and '17/08/2020 11:19:00' which tells me duration of running time.

enter image description here


Solution

  • It looks like you want the difference between each stoptime and the latest prior issue. If issues and stop times are properly interleaved, as you explained in the comments, then you can use window functions as follows:

    select t.*, stop_time - max_issue as diff
    from (
        select t.*, max(issue) over(order by issue) max_issue
        from mytable t
    ) t
    where stop_time is not null