gpt4 book ai didi

sql - 计算不包括周末和节假日的日期之间的天数的初学者方法

转载 作者:行者123 更新时间:2023-11-29 13:50:24 24 4
gpt4 key购买 nike

我是 Postgres 的初学者,正在寻求一些帮助来解决我遇到的查询问题。我正在尝试计算两个日期之间的工作日数(不包括周六和周日及节假日)。这就是我正在尝试做的事情:

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)

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

您必须手动填充其他假期或编写程序来执行此操作。

然后,要计算天数之间的差异,请执行以下操作:

 select count(*) from cal 
where cal between "start_date_var" and "end_date_var"
and business_day=true;

注意:如果是我,我会在您的日历表中添加一些其他列,以便它可以包括今天是哪个假期,或其他类似的东西。假期甚至可能还有另一张 table 。不过,这是一个好的开始。

关于sql - 计算不包括周末和节假日的日期之间的天数的初学者方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42076236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com