Generate a range of dates using SQL

前端 未结 15 1395
面向向阳花
面向向阳花 2020-11-28 05:47

I have a SQL query that takes a date parameter (if I were to throw it into a function) and I need to run it on every day of the last year.

How to generate a list of

15条回答
  •  天命终不由人
    2020-11-28 06:01

    Recently I had a similar problem and solved it with this easy query:

    SELECT
      (to_date(:p_to_date,'DD-MM-YYYY') - level + 1) AS day
    FROM
      dual
    CONNECT BY LEVEL <= (to_date(:p_to_date,'DD-MM-YYYY') - to_date(:p_from_date,'DD-MM-YYYY') + 1);
    

    Example

    SELECT
      (to_date('01-05-2015','DD-MM-YYYY') - level + 1) AS day
    FROM
      dual
    CONNECT BY LEVEL <= (to_date('01-05-2015','DD-MM-YYYY') - to_date('01-04-2015','DD-MM-YYYY') + 1);
    

    Result

    01-05-2015 00:00:00
    30-04-2015 00:00:00
    29-04-2015 00:00:00
    28-04-2015 00:00:00
    27-04-2015 00:00:00
    26-04-2015 00:00:00
    25-04-2015 00:00:00
    24-04-2015 00:00:00
    23-04-2015 00:00:00
    22-04-2015 00:00:00
    21-04-2015 00:00:00
    20-04-2015 00:00:00
    19-04-2015 00:00:00
    18-04-2015 00:00:00
    17-04-2015 00:00:00
    16-04-2015 00:00:00
    15-04-2015 00:00:00
    14-04-2015 00:00:00
    13-04-2015 00:00:00
    12-04-2015 00:00:00
    11-04-2015 00:00:00
    10-04-2015 00:00:00
    09-04-2015 00:00:00
    08-04-2015 00:00:00
    07-04-2015 00:00:00
    06-04-2015 00:00:00
    05-04-2015 00:00:00
    04-04-2015 00:00:00
    03-04-2015 00:00:00
    02-04-2015 00:00:00
    01-04-2015 00:00:00
    

提交回复
热议问题