如何查找给定年份中星期日的数量(例如:input_year = 1996)以及这些星期日的日期

问题描述 投票:0回答:1

如何在 Oracle SQL 中查找给定年份中的星期日数量。

输入:

1996

预期输出:

<date-of-sunday-1>
<date-of-sunday-2>
.............
.............
<date-of-sunday-n>
<count-of-no-of-sundays-in-that-year>
sql oracle-database plsql oracle11g
1个回答
1
投票

这是获取周日的方法:

SQL> with the_whole_year as
  2    (select trunc(to_date(&&par_year, 'yyyy'), 'yyyy') + level - 1 c_date,
  3            to_char(trunc(to_date(&&par_year, 'yyyy'), 'yyyy') + level - 1, 'fmday') c_day
  4     from dual
  5     connect by level <= add_months(trunc(to_date(&&par_year, 'yyyy'), 'yyyy'), 12) -
  6                         trunc(to_date(&&par_year, 'yyyy'), 'yyyy')
  7    )
  8  select c_date
  9  from the_whole_year
 10  where c_day = 'sunday';

C_DATE
----------
07.01.1996
14.01.1996
21.01.1996
28.01.1996
04.02.1996
11.02.1996
<snip>

我想你自己就能数得出来。


[编辑:进行计数的函数]

SQL> CREATE OR REPLACE FUNCTION f_count_of_sundays (par_year IN NUMBER)
  2     RETURN NUMBER
  3  IS
  4     retval   NUMBER;
  5  BEGIN
  6     WITH the_whole_year
  7          AS (    SELECT TRUNC (TO_DATE (par_year, 'yyyy'), 'yyyy') + LEVEL - 1
  8                            c_date,
  9                         TO_CHAR (
 10                            TRUNC (TO_DATE (par_year, 'yyyy'), 'yyyy') + LEVEL - 1,
 11                            'fmday')
 12                            c_day
 13                    FROM DUAL
 14              CONNECT BY LEVEL <=
 15                              ADD_MONTHS (
 16                                 TRUNC (TO_DATE (par_year, 'yyyy'), 'yyyy'),
 17                                 12)
 18                            - TRUNC (TO_DATE (par_year, 'yyyy'), 'yyyy'))
 19     SELECT COUNT (*)
 20       INTO retval
 21       FROM the_whole_year
 22      WHERE c_day = 'sunday';
 23
 24     RETURN retval;
 25  END;
 26  /

Function created.

SQL> select f_count_of_sundays(1996) from dual;

F_COUNT_OF_SUNDAYS(1996)
------------------------
                      52

SQL>
© www.soinside.com 2019 - 2024. All rights reserved.