根据日期范围将数据填充到表中

时间:2019-08-30 07:27:39

标签: sql oracle

我在Oracle中有一个表:

select * from leave;

--LEAVE_DTL_ID is auto incremented

LEAVE_DTL_ID   STAFF_ID START_DT  END_DT                                        
------------ ---------- --------- ---------                                     
          49        654 21-JAN-19 23-JAN-19                                     
         186         55 02-MAY-19 06-MAY-19                                     
         280        354 09-JUN-19 14-JUN-19 

我想根据相应的日期范围将START_DTEND_DT列合并到名为“ DATES”的单个列中。

例如:取LEAVE_DTL_ID = 186,它有START_DT = '02-MAY-19'END_DT = '06-MAY-19'

我想将数据填充为

LEAVE_DTL_ID   STAFF_ID DATES                                                   
------------ ---------- ---------                                               
         186         55 02-MAY-19                                               
         187         55 03-MAY-19                                               
         188         55 04-MAY-19                                               
         189         55 05-MAY-19                                               
         190         55 06-MAY-19   

有什么办法可以做到这一点?

1 个答案:

答案 0 :(得分:4)

SQL> with leave (leave_dtl_id, staff_id, start_dt, end_dt) as
  2    (select  49, 654, date '2019-01-21', date '2019-01-23' from dual union all
  3     select 186,  55, date '2019-05-02', date '2019-05-06' from dual
  4    )
  5  select
  6    (leave_dtl_id + column_value - 1) as leave_dtl_id,
  7    staff_id,
  8    (start_dt + column_value - 1) as dates
  9  from leave cross join
 10       table(cast(multiset(select level from dual
 11                           connect by level <= end_dt - start_dt + 1
 12                          ) as sys.odcinumberlist))
 13  order by staff_id, dates;

LEAVE_DTL_ID   STAFF_ID DATES
------------ ---------- --------
         186         55 02.05.19
         187         55 03.05.19
         188         55 04.05.19
         189         55 05.05.19
         190         55 06.05.19
          49        654 21.01.19
          50        654 22.01.19
          51        654 23.01.19

8 rows selected.

SQL>