connect by 補全期間日期資料
阿新 • • 發佈:2021-01-29
connect by根據START_DATE、END_DATE補全期間日期資料
1. 存在ID和PID關係欄位
使用prior:
a) 自頂向下
start with id = 1
connect by level <= (end_date - start_date) and prior id = pid
從根節點1向下查;
b) 自底向上
start with id = 1
connect by level <= (end_date - start_date) and id = prior pid
從1向上查;
2. 不存在PID關係欄位
2.1 直接使用level
connect by level <= (end_date - start_date)
存在level重複問題,因找不到父節點所致
2.2 level + prior
connect by level <= (end_date - start_date)
and prior ID = ID
2.3 level + prior + nocycle
connect by nocycle level <= (end_date - start_date)
and prior ID = ID
可以解決迴圈問題,也可以解決資料重複問題,但是不能顯示區間資料,因為nocycle 和 id = id
2.4 放棄prior,使用level
with t as(
select name
,start_date
,end_date
-- 天數從1開始
1 min_levelv
-- 天數
,(to_date(max(end_date), 'yyyy-MM-dd') - to_date(min(start_date), 'yyyy-MM-dd')) max_level
from t_c
)
select to_date(start_date, 'yyyy-MM-dd') + lv - 1 date1
,name
, start_date
,end_date
from t join (
select level lv
from dual
-- level <= t表中最大天數
connect by level <= (select max(maxlv) from t) ) t2
-- on條件限定每條資料可取lv值的範圍
on (t2.lv >= t.min_levelv and t2.lv <= t.max_level)