I'm looking for a function which adds number of business days to given date.
Holidays table
create table pyha (pyha date primary key) ;
insert into pyha values ('2018-12-24'),('2018-12-25'),('2018-12-26'),('2019-01-01');
contains holidays. Also saturday and sunday are non-business days.
I tried to create function
create or replace function add_business_day(from_date date, num_days int)
returns date
as $fbd$
with days as
(
select dd, extract(DOW from dd) dw
from generate_series(($1+ interval'1day')::date, ($1+ interval'1day'*$2+interval'10days')::date , '1 day'::interval) dd
)
select min(dd)::date
from days
where dw not in (6,0) and
dd not in (select pyha from pyha)
and dd>=$1+interval'1day'*$2+
interval'1day'*(select count(*) from pyha where pyha between $1+ interval'1day' and
$1+interval'1day'*$2 )
$fbd$ language sql;
But it returns sometimes incorrect result:
add_business_day('2018-12-08',2)
returns 2018-12-10
but correct result is 2018-12-11
How to create such function in Postgres 9.1+ ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…