如何获取特定星期六或一个月的星期日的日期

时间:2017-03-02 09:21:21

标签: sql oracle11g oracle-sqldeveloper

我是否可以找到特定月份的星期六和星期日的某一天的日期 例如,考虑2017年1月的月份。以下日期是周末

7/1/2017 - Saturday

14/1/2017 - Saturday

21/1/2017 - Saturday

28/1/2017 - Saturday 
1/1/2017 - Sunday

8/1/2017 - Sunday

15/1/2017 - Sunday

22/1/2017 - Sunday

29/1/2017 - Sunday

我想要SQL查询,这样当我将月份和年份作为输入时,它应该给我上述所有日期(只有星期六和星期日的日期)作为输出

3 个答案:

答案 0 :(得分:0)

SQL查询中的简单调整可以为您提供所需的输出。希望这会有所帮助。

SELECT A.DT,
  TO_CHAR(A.DT,'FmDay') DAY
FROM
  (SELECT TRUNC(sysdate,'MONTH')+level DT
  FROM DUAL
    CONNECT BY level <= TO_CHAR(LAST_DAY(sysdate),'fmDD')
  )a
WHERE TO_CHAR(a.dt,'FmDAY') IN ('SATURDAY','SUNDAY');

答案 1 :(得分:0)

试试这个。在第4行,您可以将年/月组合。我以2017-02为例。

SELECT TRUNC(dt, 'MM') + LEVEL - 1 AS mdate
,to_char(TRUNC(dt, 'MM') + LEVEL - 1,'DY' ) as m_day
FROM 
(select to_date('2017-02','YYYY-MM') as dt from dual) --this is where you can put year/month
where to_char(TRUNC(dt, 'MM') + LEVEL - 1,'DY' ) in ('SAT','SUN')
CONNECT BY TRUNC(TRUNC(dt, 'MM') + LEVEL - 1, 'MM') = TRUNC(dt, 'MM')

输出

MDATE       M_DAY 
04-FEB-2017 SAT
05-FEB-2017 SUN
11-FEB-2017 SAT
12-FEB-2017 SUN
18-FEB-2017 SAT
19-FEB-2017 SUN
25-FEB-2017 SAT
26-FEB-2017 SUN

答案 2 :(得分:0)

我将对代码进行一些重大更改 我们可以获得一年中所有的周日和周六

SELECT TRUNC(dt, 'yyyy') + LEVEL - 1 AS mdate
,to_char(TRUNC(dt, 'yyyy') + LEVEL - 1,'DY' ) as m_day
FROM
(select to_date('2020-01','YYYY-MM') as dt from dual) --this is where you can put year/month
where to_char(TRUNC(dt, 'yyyy') + LEVEL - 1,'DY' ) in ('SAT','SUN')
CONNECT BY TRUNC(TRUNC(dt, 'yyyy') + LEVEL - 1, 'yyyy') = TRUNC(dt, 'yyyy')