giovedì 18 giugno 2015

Oracle: SQL for list of numbers or list of dates



For numbers:

I want to have a query which returns the list of the dates from today, for the next 10 years:

   SELECT   
     level seq,   
     _starting_ + _delta_ * level as ddate,   
   FROM DUAL  
   CONNECT BY LEVEL <= _occurrences_  


The "parameters" needed by this query are:
  • Starting: the value where to start
  • Delta: the number of days between each occurrence of the list
  • Occurrences: How many occurrences in the list (how long is the list)

For example, given the following query:

SELECT
   level seq,
   100 + 5 * level as value
FROM DUAL
CONNECT BY LEVEL <= 10

I will have this output

     SEQ   VALUE  
 ---------- ----------  
      1    105   
      2    110   
      3    115   
      4    120   
      5    125   
      6    130   
      7    135   
      8    140   
      9    145   
     10    150   
  10 Zeilen gewählt  



For dates:

I want to have a query which returns the list of the dates from today, for the next 10 years:

   SELECT   
     level seq,   
     to_date(_starting_date_, 'yyyymmdd') + _delta_ * level as ddate,   
     to_char(to_date(_starting_date_, 'yyyymmdd') + _delta_ * level, 'yyyy-ww') as week,   
     to_char(to_date(_starting_date_, 'yyyymmdd') + _delta_ * level, 'yyyy-mm') as month  
   FROM DUAL  
   CONNECT BY LEVEL <= _occurrences_  


The "parameters" needed by this query are:
  • Starting_date: the date where to start
  • Delta: the number of days between each occurrence of the list
  • Occurrences: How many occurrences in the list (how long is the list)


For example, given the following query:
   SELECT   
     level seq,   
     to_date('20140101', 'yyyymmdd') + 7 * level as ddate,   
     to_char(to_date('20140101', 'yyyymmdd') + 7 * level, 'yyyy-ww') as week,   
     to_char(to_date('20140101', 'yyyymmdd') + 7 * level, 'yyyy-mm') as month  
   FROM DUAL  
   CONNECT BY LEVEL <= 10  


I will have this output

     SEQ DDATE  WEEK  MONTH   
 ---------- -------- ------- -------  
      1 08.01.14 2014-02 2014-01   
      2 15.01.14 2014-03 2014-01   
      3 22.01.14 2014-04 2014-01   
      4 29.01.14 2014-05 2014-01   
      5 05.02.14 2014-06 2014-02   
      6 12.02.14 2014-07 2014-02   
      7 19.02.14 2014-08 2014-02   
      8 26.02.14 2014-09 2014-02   
      9 05.03.14 2014-10 2014-03   
     10 12.03.14 2014-11 2014-03   
  10 Zeilen gewählt  






Nessun commento:

Posta un commento