Analytical functions still work on datasets. They do not process one row at a time, for this you will need PL / SQL or MODEL. PRECEDING
refers to the last X lines, but before applying the analytic function.
These problems can be confusing in SQL because you need to build logic in the definition of a set instead of trying to pass data from one row to another. This is why I used CASE
with LAST_VALUE
in the previous answer.
Edit:
I added a simple dataset so that we can run the same query. VALUE1
seems to be working with me, am I missing something? Part of the problem with VALUE2
is that analytic ORDER BY uses VALUE instead of date.
select id, the_date, value ,last_value(value ignore nulls) over (partition by id order by the_date) value1 ,nvl(value, LAST_VALUE(value IGNORE NULLS) over (order by value RANGE BETWEEN 1 PRECEDING AND CURRENT ROW)) value2 from ( select 1 id, date '2011-01-01' the_date, 100 value from dual union all select 1 id, date '2011-01-02' the_date, null value from dual union all select 1 id, date '2011-01-03' the_date, null value from dual union all select 1 id, date '2011-01-04' the_date, null value from dual union all select 1 id, date '2011-01-05' the_date, 200 value from dual ) order by the_date;
Results:
ID THE_DATE VALUE VALUE1 VALUE2 1 1/1/2011 100 100 100 1 1/2/2011 100 1 1/3/2011 100 1 1/4/2011 100 1 1/5/2011 200 200 200
source share