HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Count business days between 2 dates in postgreSQL

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqlbusinessdatesbetweencountdays

Problem

I am trying to count business days between a certain date range in PostgreSQL.

My table:

|start_date |end_date |
------------------------
|2017-06-01 |2017-06-01| 
|2017-05-29 |2017-06-02|


This is my code:

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


My OUTPUT:

|start_date(date)| end_date(date) |theDiff(integer)
      ---------------------------------------------------
      |2017-06-01      |  2017-06-01    |        29     |
      |2017-05-29      |  2017-06-02    |        12     |
      ---------------------------------------------------


Expected Output:

|start_date(date)| end_date(date) |theDiff(integer)
      ---------------------------------------------------
      |2017-06-01      |  2017-06-01    |        1      |
      |2017-05-29      |  2017-06-02    |        5      |
      ---------------------------------------------------

Solution

Here is a function for calculating Business Days between two dates simmilar to networkdays excel formula. Doesn't support Holiday list yet.

create or replace function count_business_days(from_date date, to_date date)
returns bigint
as $fbd$
    select count(d::date) as d
    from generate_series(from_date, to_date, '1 day'::interval) d
    where extract('dow' from d) not in (0, 6) 
$fbd$ language sql;


Usage

SELECT issue_id, start_date, live_date, count_business_days(
    TO_DATE(start_date, 'YYYY-MM-DD'),
    TO_DATE(live_date, 'YYYY-MM-DD')
    ) as businessdays
    FROM atable;

Code Snippets

create or replace function count_business_days(from_date date, to_date date)
returns bigint
as $fbd$
    select count(d::date) as d
    from generate_series(from_date, to_date, '1 day'::interval) d
    where extract('dow' from d) not in (0, 6) 
$fbd$ language sql;
SELECT issue_id, start_date, live_date, count_business_days(
    TO_DATE(start_date, 'YYYY-MM-DD'),
    TO_DATE(live_date, 'YYYY-MM-DD')
    ) as businessdays
    FROM atable;

Context

StackExchange Database Administrators Q#207701, answer score: 8

Revisions (0)

No revisions yet.