i have a table like this:
Number Price Type Date Time
------ ----- ---- ---------- ---------
23456 0,665 SV 2014/02/02 08:00:02
23457 1,3 EC 2014/02/02 07:50:45
23460 0,668 SV 2014/02/02 07:36:34
For each EC I need previous/next SV price. In this case, the query is simple.
Select Lag(price, 1, price) over (order by date desc, time desc),
Lead(price, 1, price) over (order by date desc, time desc)
from ITEMS
But, there are some special cases where two or more rows are EC type:
Number Price Type Date Time
------ ----- ---- ---------- ---------
23456 0,665 SV 2014/02/02 08:00:02
23457 1,3 EC 2014/02/02 07:50:45
23658 2,4 EC 2014/02/02 07:50:45
23660 2,4 EC 2014/02/02 07:50:48
23465 0,668 SV 2014/02/02 07:36:34
can I use Lead/Lag in this cases? If not, did I have to use a subquery?
Yes, you can use LEAD/LAG. You just need to precalculate how far to jump with a little ROW_NUMBER() magic.
Your question (and Anon's excellent answer) is part of the SQL of islands and gaps. In this answer, I will try to examine the "row_number() magic" in detail.
I've made a simple example based on events in a ballgame. For each event, we'd like to print the previous and next quarter related message:
Here's a query showing off the "row_number() magic" approach:
row_number()
s. The first is1 2 3
for each row in the table. The secondrow_number()
places pause announcements in one list, and other events in a second list. The difference between the two,rn1 - rn2
, is unique for each section of the game. It's helpful to check difference in the example output: it's in thegroup_nr
column. You'll see that each value corresponds to one section of the game.1 2 3
for the ascending order, and3 2 1
for the descending order.lag()
andlead()
how far to jump. We have to lagrank_asc
rows to find the final row of the previous section. To find the first row of the next section, we have to leadrank_desc
rows.Hope this helps clarifying the "magic" of Gaps and Islands. Here is a working example at SQL Fiddle.