Generate a range of dates using SQL

前端 未结 15 1301
面向向阳花
面向向阳花 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:03

    Another simple way to get 365 days from today would be:

    SELECT (TRUNC(sysdate) + (LEVEL-366)) AS DATE_ID
    FROM DUAL connect by level <=( (sysdate)-(sysdate-366));
    
    0 讨论(0)
  • 2020-11-28 06:04

    Oracle specific, and doesn't rely on pre-existing large tables or complicated system views over data dictionary objects.

    SELECT c1 from dual
      MODEL DIMENSION BY (1 as rn)  MEASURES (sysdate as c1)
      RULES ITERATE (365) 
      (c1[ITERATION_NUMBER]=SYSDATE-ITERATION_NUMBER)
    order by 1
    
    0 讨论(0)
  • 2020-11-28 06:05
     SELECT (sysdate-365 + (LEVEL -1)) AS DATES
     FROM DUAL connect by level <=( sysdate-(sysdate-365))
    

    if a 'from' and a 'to' date is replaced in place of sysdate and sysdate-365, the output will be a range of dates between the from and to date.

    0 讨论(0)
  • 2020-11-28 06:07

    I don't have the answer to re-use the digits table but here is a code sample that will work at least in SQL server and is a bit faster.

    print("code sample");
    
    select  top 366 current_timestamp - row_number() over( order by l.A * r.A) as DateValue
    from (
    select  1 as A union
    select  2 union
    select  3 union
    select  4 union
    select  5 union
    select  6 union
    select  7 union
    select  8 union
    select  9 union
    select  10 union
    select  11 union
    select  12 union
    select  13 union
    select  14 union
    select  15 union
    select  16 union
    select  17 union
    select  18 union
    select  19 union
    select  20 union
    select  21 
    ) l
    cross join (
    select 1 as A union
    select 2 union
    select 3 union
    select 4 union
    select 5 union
    select 6 union
    select 7 union
    select 8 union
    select 9 union
    select 10 union
    select 11 union
    select 12 union
    select 13 union
    select 14 union
    select 15 union
    select 16 union
    select 17 union
    select 18
    ) r
    print("code sample");
    
    0 讨论(0)
  • 2020-11-28 06:08

    About a year and a half too late, but for posterity here is a version for Teradata:

    SELECT calendar_date 
    FROM SYS_CALENDAR.Calendar
    WHERE SYS_CALENDAR.Calendar.calendar_date between '2010-01-01' (date) and '2010-01-03' (date)
    
    0 讨论(0)
  • 2020-11-28 06:08

    Ahahaha, here's a funny way I just came up with to do this:

    select SYSDATE - ROWNUM
    from shipment_weights sw
    where ROWNUM < 365;
    

    where shipment_weights is any large table;

    0 讨论(0)
提交回复
热议问题