简体   繁体   中英

Query to find the last week day of every month in year using oracle sql

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

Try this:

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
)

Output:

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

Note that if your nls_territory is different, you may have to tweak the decode.

Following up on what Ed's hint and tbone's code. Formats the date the way you want. The FMDAY formatter removes extra spaces after the day of the week.

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM