In this sample table fruits, I want to get previous row, current row and next row where high_low_adjstmnt < 0.
Table
id name low high high_low_adjstmnt volume
1 Apple 5 3 -2 1000
2 Orange 6 9 3 2000
3 Banana 13 17 4 3000
4 Avocado 11 19 8 4000
5 Berry 21 17 -4 5000
6 Peach 7 9 2 6000
7 Mango 9 14 5 7000
8 Grape 18 11 7 8000
9 Kiwi 14 13 -1 9000
Desired output Result
id name low high high_low_adjstmnt volume
1 Apple 5 3 -2 1000
2 Orange 6 9 3 2000
4 Avocado 11 19 8 4000
5 Berry 21 17 -4 5000
6 Peach 7 9 2 6000
8 Grape 18 11 7 8000
9 Kiwi 14 13 -1 9000
How could I get this result in query?
2
Answers
I think there’s a few ways to approach this. Perhaps, you can use
LAG()
andLEAD()
functions to get the previous and next row value then usecte
(or derived table) to filter them like this:Demo fiddle
You can do
self-join
to get previous, current and next rows using the conditiont.id = t2.id - 1 or t.id = t2.id or t.id = t2.id + 1
.Result :
Demo here