Reputation: 171
This is my table
ID NAME YEAR PRICE
--- ------ ------ -------
1 A 2015 3
1 A 2016 4
1 A 2017 7
2 B 2015 4
2 B 2016 2
2 B 2017 6
Need Output this
ID NAME LEAD YEAR LEAD_SAL PRICE PRICE
---- ------ ------ ------ --------- ------- ------
1 A 2016 2015 4 3 1
1 A 2017 2016 7 4 3
1 A 2017 7
2 B 2016 2015 2 4 -2
2 B 2017 2016 6 2 4
2 B 2017 6
My query
SELECT id, name, LEAD(year,1,NULL) OVER (PARTITION BY id ORDER BY year) lead, year
, LEAD(price,1,NULL) OVER (PARTITION BY id ORDER BY price) lead_sal, price
, LEAD(price,1,NULL) OVER (PARTITION BY id ORDER BY price) - Price Price
FROM price_tb;
But answer comes like this
ID NAME LEAD YEAR LEAD_SAL PRICE PRICE
---- ------ ------ ------ --------- ------- ------
1 A 2016 2015 4 3 1
1 A 2017 2016 7 4 3
1 A 2017 7
2 B 2016 2015 6 4 2
2 B 2017 2016 4 2 2
2 B 2017 6
Here id 1 works fine but id 2 gives output deviated from expected. How can i rewrite this query?
Upvotes: 0
Views: 70
Reputation: 142968
How about
SQL> with test (id, name, year, price) as
2 (select 1, 'A', 2015, 3 from dual union all
3 select 1, 'A', 2016, 4 from dual union all
4 select 1, 'A', 2017, 7 from dual union all
5 --
6 select 2, 'B', 2015, 4 from dual union all
7 select 2, 'B', 2016, 2 from dual union all
8 select 2, 'B', 2017, 6 from dual
9 )
10 select
11 id,
12 name,
13 lead(year) over (partition by id order by year) lead_year,
14 year,
15 lead(price) over (partition by id order by year) lead_price,
16 price,
17 --
18 lead(price) over (partition by id order by year) - price diff
19 from test
20 order by id, year;
ID N LEAD_YEAR YEAR LEAD_PRICE PRICE DIFF
---------- - ---------- ---------- ---------- ---------- ----------
1 A 2016 2015 4 3 1
1 A 2017 2016 7 4 3
1 A 2017 7
2 B 2016 2015 2 4 -2
2 B 2017 2016 6 2 4
2 B 2017 6
6 rows selected.
SQL>
Upvotes: 1