Find all pairs of subscriptions of the same user whose date ranges overlap, and report the dates the two subscriptions have in common. Two subscriptions overlap when each one starts strictly before the other ends.
Input Table(s)
subscriptions
| Column | Type | Meaning |
|---|
| subscription_id | INT | Subscription identifier. Primary key. |
| user_id | INT | Subscriber. Not null. |
| start_date | DATE | Start date of the subscription. Not null. |
| end_date | DATE | End date of the subscription. Not null, always after start_date. |
Key: subscription_id is the primary key.
Output Contract
Columns, in this order:
| Column | Meaning |
|---|
| user_id | The user who owns both subscriptions |
| subscription_id_1 | The smaller subscription id in the pair |
| subscription_id_2 | The larger subscription id in the pair |
| overlap_start | The later of the two start dates |
| overlap_end | The earlier of the two end dates |
-
One row per overlapping pair.
-
Order by
user_id
,
subscription_id_1
,
subscription_id_2
, all ascending. Each pair of ids appears once, so the order is fully determined.
-
Return an empty result if no pair overlaps.
Example
subscriptions
| subscription_id | user_id | start_date | end_date |
|---|
| 10 | 300 | 2024-01-01 | 2024-03-01 |
| 11 | 300 | 2024-02-01 | 2024-04-01 |
| 12 | 300 | 2024-03-15 | 2024-06-01 |
| 13 | 400 | 2024-01-01 | 2024-12-31 |
Expected output:
| user_id | subscription_id_1 | subscription_id_2 | overlap_start | overlap_end |
|---|
| 300 | 10 | 11 | 2024-02-01 | 2024-03-01 |
| 300 | 11 | 12 | 2024-03-15 | 2024-04-01 |
Subscriptions 10 and 11 share 2024-02-01 to 2024-03-01, and subscriptions 11 and 12 share 2024-03-15 to 2024-04-01. Subscription 10 ends on 2024-03-01, before subscription 12 starts on 2024-03-15, so that pair does not overlap. User 400 has a single subscription and therefore no pair.
Constraints and Clarifications
-
subscriptions
has at most 10,000 rows.
-
start_date
is strictly before
end_date
for every subscription.
-
The overlap test is strict. If one subscription ends on 2024-03-01 and another starts on 2024-03-01, they do not overlap and produce no row.
-
Only subscriptions of the same user are compared.
-
Two subscriptions with identical dates overlap, and their shared window is that full range.
-
If three subscriptions of one user all overlap one another, the output has three rows, one per pair.