Skip to content
Advertisement

Find rows with adjourning date ranges and accumulate their durations

My PostgreSQL database stores school vacation, public holidays and weekend dates for parents to plan their vacation. Many times school vacations are adjourned by weekends or public holidays. I want to display the total number of non-school days for a school vacation. That should include any adjourned weekend or public holiday.

Example Data

locations

holiday_or_vacation_types

“Herbst” is German for “autumn” and “Wochenende” is German for “weekend”.

periods

Task

I want to select all periods where location_id equals 2. And I want to calculate the duration of each period in days. That can be done with this SQL query:

Any human looking at the calendar would see that the ids 670 (weekend), 532 (fall vacation) and 533 (fall vacation) are adjourned. So they add up to a 6 day vacation period. So far I do this with a program which computes this. But that takes quite a lot of resources (the actual table contains some 500,000 items).

Problem 1

Which SQL query would result in the following output (is adds a real_duration column)? Is that even possible with SQL?

Problem 2

It is possible to list the adjourning periods in a part_of_range field? This would be the result. Can that be done with SQL?

Advertisement

Answer

This is a gaps and islands problem. In this case you can use lag() to see where an island starts and then a cumulative sum.

The final operation is some aggregation (using window functions):

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