Skip to content
Advertisement

Sum and segment overlapping date ranges

Our HR system specifies employee assignments, which can be concurrent. Our rostering system only allows one summary assignment for a person. Therefore I need to pre-process the HR records, so rostering can determine the number of shifts a worker is expected to work on a given day.

Looking just at worker A who has two assignments, the first is for a quarter shift and the second for a half shift, but overlapping in the middle where they work .75 shifts.

Required output.

Given this data, how do we sum and segment the data? I found an exact question for MySQL but the version was too early and code was suggested. I also found a Postgres solution but we don’t have ranges.

Advertisement

Answer

It looks like a Gaps-and-Islands to me.

If it helps, cte1 is used to expand the date ranges via an ad-hoc tally table. Then cte2 is used to create the Gaps-and-Islands. The final result is then a small matter of aggregation.

Example

Returns

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement