Oracle(10g)相当于DATEADD(工作日,-3,GETDATE())

时间:2011-04-14 21:56:28

标签: oracle oracle10g date-arithmetic

我正在寻找相当于Oracle的Oracle(10g):

DATEADD(weekday, -3, GETDATE())

来自T-SQL(SQL Server)。从当前日期开始subtracts 3 weekdays。我不关心假期或类似的事情(我可以​​将时间截断自己)。只是排除周末是好的。

2 个答案:

答案 0 :(得分:5)

可以在没有PL / SQL功能的情况下完成。只需减去不同的天数,具体取决于星期几:

select trunc(sysdate) - case to_char(sysdate, 'D')
                        when '4' then 3 -- thursday minus 3 days
                        when '5' then 3 -- friday minus 3 days
                        when '6' then 4 -- saturday minus 4 days
                        else 5          -- all other days minus 5 days
                        end
from dual;

当您必须执行此操作时,例如12天后,它看起来像:

select trunc(sysdate) - case to_char(sysdate, 'D')
                        when '1' then 18 -- mondays minus 18 days (incl. 3 weekends)
                        when '2' then 18 -- tuesdays minus 18 days (incl. 3 weekends)
                        when '6' then 17 -- saturdays minus 17 days (incl. 2 weekends and a saturday)
                        else 16          -- all others minus 16 days (incl. 2 weekends)
                        end
from dual;

请注意,星期几取决于数据库的NLS_TERRITORY(在美国第1天是星期日,大多数情况下第1天是星期一)。

答案 1 :(得分:2)

看起来你需要创建一个UDF。

CREATE OR REPLACE FUNCTION business_date (start_date DATE, 
days2add NUMBER) RETURN DATE IS
 Counter NATURAL := 0;
 CurDate DATE := start_date;
 DayNum POSITIVE;
 SkipCntr NATURAL := 0;
 Direction INTEGER := 1;  -- days after start_date
 BusinessDays NUMBER := Days2Add;
BEGIN
  IF Days2Add < 0 THEN
    Direction := - 1; -- days before start_date
    BusinessDays := (-1) * BusinessDays;
  END IF;

  WHILE Counter < BusinessDays LOOP
    CurDate := CurDate + Direction;
    DayNum := TO_CHAR( CurDate, 'D');

    IF DayNum BETWEEN 2 AND 6 THEN
      Counter := Counter + 1;
    ELSE
      SkipCntr := SkipCntr + 1;
    END IF;
  END LOOP;

  RETURN start_date + (Direction * (Counter + SkipCntr));
END business_date;

来自here的Larry Benton的礼貌。