[英]Fill the Gap of missing data in table with smooth average using oracle query
[英]Oracle query to fill in the missing data in the same table
您可以使用遞歸查詢來生成日期,然后cross join
其與表中可用的不同id
列表cross join
。 然后,使用窗口函數帶上缺失的鍵值:
with recursive cte (mon) as (
select date '2019-01-01' mon from dual
union all select add_months(mon, 1) from cte where mon < date '2020-10-01'
)
select i.id,
coalesce(
t.status_key,
lead(t.previous_status_key ignore nulls) over(partition by id order by c.mon)
) as status_key,
coalesce(
t.status_key,
lag(t.status_key ignore nulls, 1, -1) over(partition by id order by c.mon)
) previous_status_key,
c.mon
from cte c
cross join (select distinct id from mytable) i
left join mytable t on t.mon = c.mon and t.id = i.id
您沒有詳細說明如何帶上丟失的status_key
和previous_status_key
。 這是查詢的作用:
status_key
取自下一個非null
previous_status_key
previous_status_key
取自最后一個非null
status_key
,默認值為-1
您可以生成日期,然后使用cross join
和一些附加邏輯來獲取您想要的信息:
with dates (mon) as (
select date '2019-01-01' as mon
from dual
union all
select mon + interval '1' month
from dates
where mon < date '2021-01-01'
)
select d.mon, i.id,
coalesce(t.status_key,
lag(t.status_key ignore nulls) over (partition by i.id order by d.mon)
) as status_key,
coalesce(t.previous_status_key,
lag(t.previous_status_key ignore nulls) over (partition by i.id order by d.mon)
) as previous_status_key
from dates d cross join
(select distinct id from t) i left join
t
on d.mon = t.mon and i.id = i.id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.