查询使用oracle sql查找一年中每个月的最后一周

时间:2013-06-04 13:54:17

标签: sql oracle

查询应返回每个月的最后一周。例如,如果2013年3月的最后一周是星期日,则查询应显示2013年3月29日(星期五)。

2 个答案:

答案 0 :(得分:1)

试试这个:

select dte as last_day, dayofweek_abbr as original_dayofweek, 
dte - (decode(dayofweek, 7, 1, 1, 2, 0)) as last_weekday_america
from (
    select last_day(to_date(to_char(level, '09') || '2013', 'MMYYYY')) as dte,
    to_char(last_day(to_date(to_char(level, '09') || '2013', 'MMYYYY')), 'D') as dayofweek,
    to_char(last_day(to_date(to_char(level, '09') || '2013', 'MMYYYY')), 'DAY') as dayofweek_abbr
    from dual
    connect by level <= 12
)

输出:

LAST_DAY    ORIGINAL_DAYOFWEEK  LAST_WEEKDAY_AMERICA
1/31/2013   THURSDAY    1/31/2013
2/28/2013   THURSDAY    2/28/2013
3/31/2013   SUNDAY      3/29/2013
4/30/2013   TUESDAY     4/30/2013
5/31/2013   FRIDAY      5/31/2013
6/30/2013   SUNDAY      6/28/2013
7/31/2013   WEDNESDAY   7/31/2013
8/31/2013   SATURDAY    8/30/2013
9/30/2013   MONDAY      9/30/2013
10/31/2013  THURSDAY    10/31/2013
11/30/2013  SATURDAY    11/29/2013
12/31/2013  TUESDAY     12/31/2013

请注意,如果您的nls_territory不同,则可能需要调整解码。

答案 1 :(得分:0)

跟进Ed的提示和tbone的代码。以您希望的方式格式化日期。 FMDAY格式化程序在一周之后删除多余的空格。

SELECT dte AS last_day, 
       dayofweek_abbr AS original_dayofweek, 
       to_char(dte - (decode(dayofweek, 7, 1, 1, 2, 0)),'DD MON YYYY(FMDAY)') AS     last_weekday_america
FROM (
      SELECT last_day(to_date(to_char(level, '09') || '2013', 'MMYYYY')) as dte,
             to_char(last_day(to_date(to_char(level, '09') || '2013', 'MMYYYY')), 'D') as dayofweek,
             to_char(last_day(to_date(to_char(level, '09') || '2013', 'MMYYYY')), 'DAY') as      dayofweek_abbr
      FROM dual
      CONNECT BY LEVEL <= 12
)