select pdat
,ac_no
, bal
from dummy_table;
PDATE | AC_NO | BAL
========================
14/02/2012| abcd | 1200
15/02/2012| abcd | 1300
27/02/2012| abcd | 1300
My question is how can I make the result set to fetch
PDATE | AC_NO | BAL | Difference
=====================================
14/02/2012| abcd | 1200 | 8
22/02/2012| abcd | 1300 | 7
Difference of row one is calculated on the basis of 22/02/2012-14/02/2012.
But how can I calculate the difference of last date from the month’s ending date? in this case 29th Feb 2012
Key here is
LEAD function– read documentation aboutanalytical functions in SQL, they are very powerful tool.LEAD(pdat) OVER (ORDER BY pdat)gets you value of pdat innext rowwhich comes inascending order of pdat. Thennvl functiontakes care aboutlast datewhere there isno next date– it useslast_day(pdat)function call which returns last day of a month pdat falls in.If you want to handle several months – you will need to do some analysis with
DECODE functionto detect if pdat andLEAD(pdat) OVER (ORDER BY pdat)belong to the same month, and to use eitherLEAD(pdat) OVER (ORDER BY pdat)or last_day(pdat) as date you are comparing against. I will leave it as your homework.