I have a simple table of date ranges each with an associated number of hours per week:
CREATE TABLE tmp_ranges (
id SERIAL PRIMARY KEY,
rng daterange,
hrs_
Here is my attempt to solve this problem:
select y,
sum( hrs_per_week )
from tmp_ranges t
join(
select daterange( x,
lead(x) over (order by x) ) As y
from (
select lower( rng ) As x
from tmp_ranges
union
select upper( rng )
from tmp_ranges
order by x
) y
) y
on t.rng && y.y
group by y
order by y
Demo: http://sqlfiddle.com/#!15/ef6cb/13
The innermost subquery collects all boundary dates into one set using union
, then sorts them.
Then the outer subquery builds new ranges from adjacent dates using lead
function.
In the end, these new ranges are joined to the source table in the main query, aggregated, and sum
is calculated.
EDIT
The order by
clause in the innermost query is redundant and can be skipped, because lead(x) over
caluse orders records by dates, and a resultset from the innermost subquery doesn't have to be sorted.