2017-07-17 56 views
0

我必須使用oracle日程安排查找最近5個工作日。Oracle Schdule上的最後5個工作日(排除週六和週日)

select sysdate as current_date, 
     case when to_char(sysdate,'D') in (1,2,7) 
      then next_day(sysdate-7,'Friday') 
      else sysdate-1 end as prev_weekday1, 
     case when to_char(sysdate,'D') in (1,2,7) 
      then next_day(sysdate-7,'Friday') 
      else sysdate-2 end as prev_weekday2, 
     case when to_char(sysdate,'D') in (1,2,7) 
      then next_day(sysdate-7,'Friday') 
      else sysdate-3 end as prev_weekday3, 
     case when to_char(sysdate,'D') in (1,2,7) 
      then next_day(sysdate-7,'Friday') 
      else sysdate-4 end as prev_weekday4, 
     case when to_char(sysdate,'D') in (1,2,7) 
      then next_day(sysdate-7,'Friday') 
      else sysdate-5 end as prev_weekday5 
from dual 

請幫助我是這種方式是正確的或任何其他優化的方式是有。

+0

調度不能在運行最近幾個工作日,因爲他們已經發生。調度程序如何適應您的問題? – Ben

回答

1

select level from dual connect by level <=7爲等級提供結果1..7。

使用此,選擇最後七天,除去星期六和星期日:

select 'prev_weekday_' || rownum as prev_weekday, d.dt 
    from (select trunc(sysdate) - level dt, 
       to_char(sysdate - level, 'D') w_day 
      from dual 
     connect by level <= 7) d 
where d.w_day <= 5 
order by d.dt desc; 

/* 
prev_weekday_1 14.07.2017 
prev_weekday_2 13.07.2017 
prev_weekday_3 12.07.2017 
prev_weekday_4 11.07.2017 
prev_weekday_5 10.07.2017 
*/ 

如果您需要在列的結果則支點:

select * 
    from (select 'prev_weekday_' || rownum as prev_weekday, d.dt 
      from (select trunc(sysdate) - level dt, 
         to_char(sysdate - level, 'D') w_day 
        from dual 
       connect by level <= 7) d 
     where d.w_day <= 5 
     order by d.dt desc) 
pivot(max(dt) 
    for prev_weekday in('prev_weekday_1' as prev_weekday_1, 
         'prev_weekday_2' as prev_weekday_2, 
         'prev_weekday_3' as prev_weekday_3, 
         'prev_weekday_4' as prev_weekday_4, 
         'prev_weekday_5' as prev_weekday_5)); 
/* 
prev_weekday_1 prev_weekday_2 prev_weekday_3 prev_weekday_4 prev_weekday_5 
    14.07.2017  13.07.2017  12.07.2017  11.07.2017  10.07.2017 
*/ 
相關問題