且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

初学者计算日期之间的天数(不包括周末和节假日)

更新时间:2023-01-31 14:14:49

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)

现在您有一个日历表,其中周末设置为 business_day = false,所有其他日期设置为true。

Now you have a calendar table populated with weekends set to "business_day=false" and all other days set to 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.