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

标签 sql postgresql count

我是 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/

相关文章:

javascript - Objection.js - 查询生成器不是使用插入方法的函数

mysql - 同时选择连接表行的计数和计数总和

mysql - 当 SQL 中列中的值不明确时,如何使用 where 子句?

sql - 点和多边形之间的 STDistance 始终返回 0,即使它们相距数英里

mysql - SQL 搜索午夜到午夜

sql - 使用 PostgreSQL 在 SQL 查询中创建一个空数组,而不是内部包含 NULL 的数组

sql - 如何检索通过 insert...select 插入的行的标识?

delphi - Lazarus Free Pascal/Delphi - 运行错误 211

mysql - 在 MySQL 中计算选票

java - 从多个集合中找到最大匹配计数集合