问题
I'm looking for the Oracle (10g) equivalent of:
DATEADD(weekday, -3, GETDATE())
from T-SQL (SQL Server) . This subtracts 3 weekdays from the current date. I'm not concerned about holidays or anything like that (and I can truncate the time part off myself). Just excluding weekends is fine.
回答1:
It looks like you need to create a 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;
Courtesy of Larry Benton, from here.
回答2:
It can be done without a PL/SQL function. Just subtract a different number of days depending on the day of the week:
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;
When you have to do this for e.g. 12 days back, it would look like:
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;
Please note that day of week depends on the NLS_TERRITORY of your database (in America day 1 is Sunday, in most others day 1 is Monday).
来源:https://stackoverflow.com/questions/5670194/oracle-10g-equivalent-of-dateaddweekday-3-getdate