[SOLVED] How to take offset difference of a column without using `order by` and


This Content is from Stack Overflow. Question asked by DaveR

Right now this code is doing what it needs to do. I just feel like that the function LAG should have an easier way to take basically OFFSET=-1, which is not possible so I have to resort to the current code. What I do not like is that is every time I need this functionality I need to add 2 lines: 1 in the SELECT statement, 1 in the ORDER BY statement. Is there a cleaner way to achieve the same result in 1 line?

I do not care if LAG is replaced by another function, I am just interested in the final result being the same.

WITH mytable AS (
    ) AS t (time)
SELECT time,
       LAG(time) OVER (ORDER BY time ASC) AS lagged_time
FROM mytable


LAG(time) OVER (ORDER BY time ASC) == LEAD(time) OVER (ORDER BY time DESC). An ORDER BY clause is the only method to ensure output is sorted as needed. You must include the clause if a specific ordering is requried.

This Question was asked in StackOverflow by DaveR and Answered by Serg It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?