[英]Beginner way to count days between dates excluding weekends and holidays
I am a beginner in Postgres and looking for some help on a problem I am having with a query. 我是Postgres的初学者,正在寻找一些有关查询问题的帮助。 I am trying to count the number of business days between two dates (exclude sat & sun & holidays).
我想计算两个日期之间的工作日数(不包括sat&sun和holiday)。 This is kind of what I am trying to do:
这就是我想要做的事情:
Select column1, column2, (current_date - defined_date) as elapsed_days
from mytable
where elapsed_days excludes sat, sun, and holidays
create table calendar c as
(cal_date date primary key,
business_day boolean not null);
insert into calendar
(select
('01/01/1900'::date + (g||' days')::interval)::date,
case extract(dow from '01/01/1900'::date
+ (g||' days')::interval)
when 0 then false when 6 then false else true end
from generate_series(0,365*150) g)
Now you have a calendar table populated with weekends set to "business_day=false" and all other days set to true. 现在,您有一个日历表,其中周末设置为“business_day = false”,所有其他日期设置为true。
You'll have to populate your other holidays manually or write a program to do that. 您必须手动填充其他假期或编写程序来执行此操作。
Afterwards, to calculate difference between days do something like: 之后,要计算天数之间的差异,请执行以下操作:
select count(*) from cal
where cal between "start_date_var" and "end_date_var"
and business_day=true;
NOTE: If it were me, I'd add a few other columns to your calendar table so that it can include which holiday it is, or other things like that. 注意:如果是我,我会在您的日历表中添加一些其他列,以便它可以包括它是哪个假期,或其他类似的东西。 May even have another table for holidays.
甚至还有另一张假期表。 This is a good start though.
这是一个好的开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.