Need Oracle SQL to split up date/time range by day

前端 未结 2 544
自闭症患者
自闭症患者 2020-12-21 04:13

I am hoping to get some help to write some SQL that I have had no success writing myself.

I have a table with the data:

ID    StartDate             EndDat         


        
2条回答
  •  忘掉有多难
    2020-12-21 04:42

    It is possible to do this in SQL. There are two tricks. The first is generating a series of numbers, which you can do with a CTE using connect.

    The second is putting together the right logic to expand the dates, while keeping the right times for the beginning and end.

    The following is an example:

    with n as (
          select level n
          from dual connect by level <= 20
         ),
         t as (
          select 1 as id, to_date('01/01/2000 4', 'mm/dd/yyyy hh') as StartDate, to_date('01/03/2000 6', 'mm/dd/yyyy hh') as EndDate from dual union all
          select 2 as id, to_date('01/04/2000 8', 'mm/dd/yyyy hh') as StartDate, to_date('01/04/2000 12', 'mm/dd/yyyy hh') as EndDate from dual union all
          select 3 as id, to_date('01/05/2000', 'mm/dd/yyyy') as StartDate, to_date('01/06/2000', 'mm/dd/yyyy') as EndDate from dual
         )
    select t.id,
           (case when n = 1 then StartDate
                 else trunc(StartDate + n - 1)
            end) as StartDate,
           (case when trunc(StartDate + n - 1) = trunc(enddate)
                 then enddate
                 else trunc(StartDate + n)
            end)
    from t join
         n
         on StartDate + n - 1 <= EndDate
    order by id, StartDate
    

    Here it is on SQLFiddle.

提交回复
热议问题