How to get the value of the previous row

How to get value from previous line of SELECT statement result

If we have a table called cardevent and has the rows [ID (int), Value (Money)], and we have several rows, for example

ID --Value

1------70 
1------90
2------100
2------150
2------300 
3------150 
3------200 
3-----250 
3-----280

etc...

How to make one request that receives each row identifier, the value and the previous value of the row in which the data is displayed, as follows

ID --- Value ---Prev_Value

1 ----- 70 ----------  0 
1 ----- 90 ---------- 70
2 ----- 100 --------  90 
2 ------150 -------- 100
2 ------300 -------- 150
3 ----- 150 -------- 300 
3 ----- 200 -------- 150 
3 ---- 250 -------- 200 
3 ---- 280 -------- 250

etc.

So can anyone help me get a better solution for such a problem?

Query Request Help

+3
source share
5 answers

You will need to join the table with yourself, I'm not sure if this is 100% legal SQL, but I do not have SQL-Server to try this at the moment, but try the following:

select (ID, Value) from table as table1 join
inner join table as table2
on table1.ID = (table2.ID -1)
+5

SELECT t.*, LAG(t.Value) OVER (ORDER BY t.ID) FROM table AS t

. Lag . , , .

+2
+1
source

You can use the LAG () and LEAD () functions to get the previous and next values.

SELECT t.Value OVER (ORDER BY t.ID) PREVIOUS_VALUE,
t.value VALUE,
LEAD(t.value) OVER (ORDER BY t.ID) NEXT_VALUE
FROM TABLE T

GO
+1
source
select t1.value - t2.value from table t1, table t2 
where t1.primaryKey = t2.primaryKey - 1

Try it.

0
source

Source: https://habr.com/ru/post/1789175/


All Articles