2013-06-04 90 views
0

查詢應返回每個月的最後一週。例如,如果2013年3月的最後一週是星期天,則查詢應顯示29月3日2013(星期五)。查詢使用oracle sql查找每年的每個月的最後一週的日期sql

+2

你可以發佈你到目前爲止嘗試過的嗎? StackOverflow是關於幫助已經嘗試過並且未能解決問題的人們;這不是關於發佈作業答案。 「每個月」是什麼意思? Oracle日期範圍可以從公元前4712年到9999年ACE,因此「每月」可能意味着超過176,000個月。我可以給你這麼多:查看Oracle ['LAST_DAY'](http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions077.htm#i83733)函數。 –

+0

考慮使用日曆表。看看這個答案http://stackoverflow.com/a/5123255/472226 – Ronnis

回答

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是不同的,你可能需要調整解碼。

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 
) 
相關問題