How do I generate all the dates of Sunday between 2 dates in oracle sql?

无人久伴 提交于 2021-02-17 03:37:17

问题


How do I generate all the dates of Sunday between 2 dates in oracle SQL?

Example if I want all the Sundays between "01/10/2018" and "31/12/2018" the output

will be:
07/10/2018
14/10/2018
21/10/2018
...
30/12/2018

Also how do I generate all the dates between 2 dates?

Example: from "01/12/2018" to "31/12/2018"

Output will be:

01/12/2018
02/12/2018
03/12/2018
...
31/12/2018

回答1:


Here's how; the CTE (dates) creates a "calendar" of all dates starting from 2018-10-01, for number of days between 2018-10-01 and 2018-12-31. This answers your 2nd question.

For the 1st question, using TO_CHAR function with appropriate format mask (dy) and date language (because, if I didn't use it, you'd get Croatian names as that's my default language), select all Sundays.

SQL> with dates as
  2    (select date '2018-10-01' + level - 1 datum
  3     from dual
  4     connect by level <= date '2018-12-31' - date '2018-10-01' + 1
  5    )
  6  select datum
  7  From dates
  8  where to_char(datum, 'dy', 'nls_date_language = english') = 'sun';

DATUM
-----------
07-oct-2018
14-oct-2018
21-oct-2018
28-oct-2018
04-nov-2018
11-nov-2018
18-nov-2018
25-nov-2018
02-dec-2018
09-dec-2018
16-dec-2018
23-dec-2018
30-dec-2018

13 rows selected.

SQL>



回答2:


The following query does it.

First generate rows using connect by clause, each of the row will have the value of "level" column incremented by 1 Also get the day_of_week per date Filter out the records where day_of_week='sun'

with data
  as (
    select to_date('1/10/2018','dd/mm/yyyy')+level as sun_day
           ,to_char(to_date('1/10/2018','dd/mm/yyyy')+level,'dy') day_of_week
      from dual
    connect by level<=to_date('31/12/2018','dd/mm/yyyy') - to_date('1/10/2018','dd/mm/yyyy')  
      )
select sun_day
  from data
where day_of_week='sun'  

For the second part of the query simply remove the filter on the day_of_week

with data
  as (
    select to_date('1/10/2018','dd/mm/yyyy')+level as sun_day
           ,to_char(to_date('1/10/2018','dd/mm/yyyy')+level,'dy') day_of_week
      from dual
    connect by level<=to_date('31/12/2018','dd/mm/yyyy') - to_date('1/10/2018','dd/mm/yyyy')  
      )
select sun_day
  from data;



回答3:


select
    to_char(date,'DD-MON-YYYY')
from
    dates
where
    (trunc(date) >= '01/12/2018'
    and
        trunc(date)<= '31/12/2018')
    and
        to_char(date,'DAY') ='SUNDAY';


来源:https://stackoverflow.com/questions/53358464/how-do-i-generate-all-the-dates-of-sunday-between-2-dates-in-oracle-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!