如何选择当年的第二个星期六?

时间:2014-02-05 12:21:30

标签: oracle oracle-sqldeveloper

SELECT NEXT_DAY(NEXT_DAY((TRUNC(TO_DATE('01-JAN-2014', 'DD-MON-YYYY'),
                                'MONTH') - 1),
                         'SATURDAY'),
                'SATURDAY') SECOND_SATURDAY
  FROM DUAL;

以上查询仅显示给定月份的第二个星期六日期

但我想要检索本年度的所有第二个星期六。

提前致谢。

1 个答案:

答案 0 :(得分:1)

对您的版本进行

次要增强,首先生成所有月份的first day,然后在查询中使用该

WITH ALL_MONTHS AS
(SELECT ADD_MONTHS(TO_DATE('01-JAN-2014', 'DD-MON-YYYY'),LEVEL-1) as MONTH_FIRST_DATE 
 FROM DUAL
 CONNECT BY LEVEL<=12)
SELECT NEXT_DAY(NEXT_DAY((TRUNC(MONTH_FIRST_DATE,
                                'MONTH') - 1),
                         'SATURDAY'),
                'SATURDAY') SECOND_SATURDAY
  FROM ALL_MONTHS;

所有星期六!!

WITH ALL_SATURDAYS AS
  (SELECT TO_CHAR(TO_DATE('01012014','DDMMYYYY'),'WW')                              * (level)                                                                                       AS WEEK_NO,
    NEXT_DAY(TO_DATE('01012014','DDMMYYYY')                                         + (TO_CHAR(TO_DATE('01012014','DDMMYYYY'),'WW' ) * (level-1) * 7),'SAT')                        AS SATURDAY_DATE,
    row_number() OVER (PARTITION BY TO_CHAR(NEXT_DAY(TO_DATE('01012014','DDMMYYYY') + (TO_CHAR(TO_DATE('01012014','DDMMYYYY'),'WW' ) * (level-1) * 7),'SAT'),'MON') ORDER BY level) AS Pos
  FROM DUAL
    CONNECT BY level<= 52
  ORDER BY 1
  )
SELECT SATURDAY_DATE,POS FROM ALL_SATURDAYS WHERE POS IN (2,4) ORDER BY 1,2