簡體   English   中英

Oracle查詢填補同表中缺失的數據

[英]Oracle query to fill in the missing data in the same table

我在 oracle 中有一個表,其中缺少給定 ID 的數據。 我試圖找出從開始日期填寫數據的 sql:01/01/2019 到 end_dt:10/1/2020。 請參閱下面的輸入數據。 對於狀態鍵,可以根據其先前的狀態鍵填充數據。 見輸入:

在此處輸入圖片說明

預期輸出:

在此處輸入圖片說明

您可以使用遞歸查詢來生成日期,然后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_keyprevious_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM