connect by 补全期间日期数据

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)

猜你喜欢

转载自blog.csdn.net/weixin_38230171/article/details/113118598