compute sum of values associated with overlapping date ranges

余生长醉 提交于 2019-12-02 04:02:37

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!