Это, вероятно, можно немного упростить, но я получаю ответ, который вы хотели, я полагаю.Немного хитрый бит получает как количество дней между ненулевыми значениями (т. Е. Размер пробела, который вы заполняете), так и позицию в этом промежутке:
-- CTE for sample data
with your_table (emp, test_date, value) as (
select 'A', date '2001-01-01', null from dual
union all select 'A', date '2001-01-02', 100 from dual
union all select 'A', date '2001-01-03', null from dual
union all select 'A', date '2001-01-04', 80 from dual
union all select 'A', date '2001-01-05', null from dual
union all select 'A', date '2001-01-06', null from dual
union all select 'A', date '2001-01-07', 75 from dual
)
-- actual query
select emp, test_date, value,
coalesce(value,
(next_value - prev_value) -- v3-v1
/ (count(*) over (partition by grp) + 1) -- d3-d1
* row_number() over (partition by grp order by test_date desc) -- d2-d1, indirectly
+ prev_value -- v1
) as interpolated
from (
select emp, test_date, value,
last_value(value ignore nulls)
over (partition by emp order by test_date) as prev_value,
first_value(value ignore nulls)
over (partition by emp order by test_date range between current row and unbounded following) as next_value,
row_number() over (partition by emp order by test_date) -
row_number() over (partition by emp order by case when value is null then 1 else 0 end, test_date) as grp
from your_table
)
order by test_date;
E TEST_DATE VALUE INTERPOLATED
- ---------- ---------- ------------
A 2001-01-01
A 2001-01-02 100 100
A 2001-01-03 90
A 2001-01-04 80 80
A 2001-01-05 76.6666667
A 2001-01-06 78.3333333
A 2001-01-07 75 75
I 'мы использовали last_value
и first_value
вместо lead
и lag
, но оба работают.(Задержка / отставание может быть быстрее на большом наборе данных, я полагаю).grp
расчет Табибитозан .