Sample Header Ad - 728x90

Select groups of values that cover a date interval together

1 vote
0 answers
20 views
I have a database table with the following relevant columns: group_id, value, valid_from, valid_to None of those columns are unique (this is not the whole table). Data could look like this: | group_id | valid_from | valid_to | | -------- | ---------- | -------- | | 1 | 20250201 | 20250228 | | 2 | 20250201 | 20250228 | | 2 | 20250201 | 20250228 | | 3 | 20250201 | 20250215 | | 3 | 20250213 | 20250220 | | 3 | 20250221 | 20250228 | | 4 | 20250101 | 20250220 | | 4 | 20250210 | 20250215 | | 4 | 20250219 | 20250228 | | 5 | 20250101 | 20250115 | | 5 | 20250513 | 20250619 | So each group has one or more entries. Every entry has a date interval. The intervals can overlap and are not unique. Now I have the impossible task to determine all groups which cover a date interval together. Let's say I need to find all groups that cover the interval 20250201 - 20250228. With the test data shown, I would expect to find groups 1, 2, 3 and 4. (None of the rows of group 3 cover the interval by themselves. But they overlap and cover the interval together). I have to solve this with SQL ONLY but I can use multiple selects. I'm a SAP Dev and I try to solve this with a HANA AMDP Method / SQLScript but feel free to give me any SQL solution you can come up with. My idea was to select all of the date intervals that overlap (not cover it completely) with my needed date interval. Then use window function LAG() to select the previous date intervals of the group and check if they overlap, or if there is a gap. If they overlap, I would take the valid_from of the previous row to widen/enhance the interval. This way I was hoping to create a entry that has the maximum covered interval of the group. Then I could make one more select and look for entries that cover the whole interval.
tmp_1 = 
SELECT
 group_id,
 CASE
  WHEN valid_from = 20250201;

tmp_2 =
SELECT
 group_id
 FROM tmp_1
 WHERE valid_from_min = 20250228
GROUP BY group_id;
This only works when a group has less than 3 entries. Second row valid_from_min will equal valid_from of the first row - good. Third row valid_from_min will equal valid_from of the second row - bad.
Asked by Aprikose (11 rep)
Jul 4, 2025, 02:57 PM