我正在尝试计算 PostgreSQL 中某个日期范围之间的工作日。
我的桌子:
|start_date |end_date |
------------------------
|2017-06-01 |2017-06-01|
|2017-05-29 |2017-06-02|
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
SELECT pto.start_date, pto.end_date,
SUM(CASE WHEN extract (dow FROM foo) IN(1,2,3,4,5) THEN 1 ELSE 0 END) as theDIFF
FROM (
SELECT start_date, (start_date::date + (generate_series(0,end_date::date
- start_date::date)||'days')::interval) AS foo
FROM pto
) foo inner join pto pto
on pto.start_date = foo.start_date
group by pto.start_date, pto.end_date
Run Code Online (Sandbox Code Playgroud)
我的输出:
|start_date(date)| end_date(date) |theDiff(integer)
---------------------------------------------------
|2017-06-01 | 2017-06-01 | 29 |
|2017-05-29 | 2017-06-02 | 12 |
---------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
预期输出:
|start_date(date)| end_date(date) |theDiff(integer)
---------------------------------------------------
|2017-06-01 | 2017-06-01 | 1 |
|2017-05-29 | 2017-06-02 | 5 |
---------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
小智 8
这是一个计算两个日期之间的工作日的函数,类似于网络日 Excel 公式。尚不支持假期列表。
\n\ncreate or replace function count_business_days(from_date date, to_date date)\nreturns bigint\nas $fbd$\n\xc2\xa0 \xc2\xa0 select count(d::date) as d\n from generate_series(from_date, to_date, '1 day'::interval) d\n\xc2\xa0 \xc2\xa0 where extract('dow' from d) not in (0, 6) \n$fbd$ language sql;\n
Run Code Online (Sandbox Code Playgroud)\n\n用法
\n\nSELECT issue_id, start_date, live_date, count_business_days(\n TO_DATE(start_date, 'YYYY-MM-DD'),\n TO_DATE(live_date, 'YYYY-MM-DD')\n ) as businessdays\n FROM atable;\n
Run Code Online (Sandbox Code Playgroud)\n
您没有使用(或向我们展示)唯一的键,如果您有多于一行具有相同的(开始日期,结束日期),您将得到错误的结果。
select start_date, end_date,
sum(case when extract (dow from dt) in (1,2,3,4,5) then 1 else 0 end) as thediff
from (
select start_date, end_date,
generate_series(start_date, end_date, '1 day'::interval) as dt
from tbl
) t
group by start_date, end_date;
Run Code Online (Sandbox Code Playgroud)
开始日期 | 结束日期 | 差异 :------------------ | :------------------ | ------: 2017-05-29 00:00:00 | 2017-06-02 00:00:00 | 5 2017-06-01 00:00:00 | 2017-06-01 00:00:00 | 1
select id, start_date, end_date,
sum(case when extract (dow from dt) in (1,2,3,4,5) then 1 else 0 end) as thediff
from (
select id, start_date, end_date,
generate_series(start_date, end_date, '1 day'::interval) as dt
from tbl
) t
group by id, start_date, end_date;
Run Code Online (Sandbox Code Playgroud)
编号 | 开始日期 | 结束日期 | 差异 -: | :------------------ | :------------------ | ------: 1 | 2017-06-01 00:00:00 | 2017-06-01 00:00:00 | 1 2 | 2017-05-29 00:00:00 | 2017-06-02 00:00:00 | 5
db<>在这里摆弄
归档时间: |
|
查看次数: |
16310 次 |
最近记录: |