compute sum of values associated with overlapping date ranges

前端 未结 1 1441
梦毁少年i
梦毁少年i 2021-01-24 18:44

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_         


        
相关标签:
1条回答
  • 2021-01-24 19:17

    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.

    0 讨论(0)
提交回复
热议问题