I select some dateranges with tsrange that includes a specific year.
I recieve an output like this:
{ time_range: '("2024-12-27 00:00:00","2025-02-01 00:00:00")' },
{ time_range: '("2025-05-01 00:00:00","2025-05-05 00:00:00")' },
{ time_range: '("2025-05-08 00:00:00","2025-05-20 00:00:00")' }
can I count all days grouped by year ?
currentcode:
SELECT time_range FROM holidays WHERE time_range && tsrange($1, $2, '[)')
4
Answers
using this data:
You can write a query which gets all dates in the range, and then count them.
see: DBFIDDLE
output:
or, when you want them per daterange: DBFIDDLE
output:
You don’t seem to want a tsrange but rather a daterange. Otherwise I’ve kept your sample data. The series of CTE clauses are just to make it easier to read – you might want to merge some steps.
gives
See example.
Whether or not to include boundary dates in the calculation is an open question. For example (‘2024-03-14’, ‘2024-03-15’) =0? =1? or =2 ?
Sample data
Query
Output
Subquery result is
select sum(datediff(d,fromadate,todate)) from
table which has fromdate todate extracted from tsrange