How to iterate over a date range in PL/SQL

前端 未结 7 1895
梦毁少年i
梦毁少年i 2020-12-29 12:56

I need to write a report that generates summary totals against a table with date ranges for each record.

table data:
option   start_date   end_date
opt1              


        
相关标签:
7条回答
  • 2020-12-29 13:33

    You will need some sort of calendar to loop through a range of date. I have built one using the connect by level trick. You can then join the calendar with your data (cross join since you want a row even when there is no option for that day):

    SQL> WITH calendar AS (
      2     SELECT to_date(:begin_date, 'mm/dd/yyyy') + ROWNUM - 1 c_date
      3       FROM dual
      4      CONNECT BY LEVEL <= to_date(:end_date, 'mm/dd/yyyy') 
                                 - to_date(:begin_date, 'mm/dd/yyyy') + 1
      5  )
      6  SELECT c_date "date", d_option "option", COUNT(one_day)
      7    FROM (SELECT c.c_date, d.d_option,
      8                  CASE
      9                     WHEN c.c_date BETWEEN d.start_date AND d.end_date THEN
     10                      1
     11                  END one_day
     12             FROM DATA d, calendar c)
     13   GROUP BY c_date, d_option
     14  ORDER BY 1,2;
    
    date        option COUNT(ONE_DAY)
    ----------- ------ --------------
    01/06/2009  opt1                0
    01/06/2009  opt2                0
    02/06/2009  opt1                0
    02/06/2009  opt2                0
    03/06/2009  opt1                1
    03/06/2009  opt2                0
    04/06/2009  opt1                1
    04/06/2009  opt2                0
    05/06/2009  opt1                1
    05/06/2009  opt2                1
    06/06/2009  opt1                1
    06/06/2009  opt2                1
    
    12 rows selected
    
    0 讨论(0)
提交回复
热议问题