如何迭代PostgreSQL中的日期表,总计每个月的工作日总数

时间:2018-02-15 15:09:59

标签: postgresql

我需要帮助我认为是Postgres中的存储过程。

我需要一个日期视图,附加日期是每个月内工作日的运行计数(每月1日重置)。

我正在使用:

创建一个视图(在查询中)
January 1st 2018 | Monday | 1
January 2nd 2018 | Tuesday| 2
January 3rd 2018 | Wednesday | 3
January 4th 2018 | Thursday | 4
January 5th 2018 | Friday | 5
January 6th 2018 | Saturday | 5
January 7th 2018 | Sunday | 5
...
February 1st 2018 | Thursday | 1

输出看起来像这样:

{{1}}

关键是非工作日(周末)不增加,计数在每个月的第一天重置。

谢谢! 汤姆

1 个答案:

答案 0 :(得分:1)

with dates as (
  select generate_series('2018-01-01', current_date - 1, interval '1 day')::date as _day order by 1 asc
)
select 
  _day,
  sum(case when date_part('dow', _day) in (1,2,3,4,5) then 1 else 0 end) over (partition by date_part('month', _day) order by _day)
from dates;