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 |
---------------------------------------------------