SQL -problem -subscription

Source:https://www.interviewquery.com/questions/subscription-overlap

Given a table of product subscriptions with a subscription start date and end date for each user, write a query that returns true or false whether or not each user has a subscription date range that overlaps with any other completed subscription.

Completed subscriptions have end_date recorded.

Example:

Input:

subscriptions table

ColumnType
user_idINTEGER
start_dateDATETIME
end_dateDATETIME
user_idstart_dateend_date
12019-01-012019-01-31
22019-01-152019-01-17
32019-01-292019-02-04
42019-02-052019-02-10

Output:

user_idoverlap
11
21
31
40
WITH over_lap AS (
    SELECT s2.start_date, s2.end_date, s2.user_id, 1 AS is_overlap
    FROM subscriptions s1
    JOIN subscriptions s2 ON s1.user_id != s2.user_id
    AND (
        s2.start_date BETWEEN s1.start_date AND s1.end_date
        OR s2.end_date BETWEEN s1.start_date AND s1.end_date
    )
)
-- Get users with overlaps
SELECT c.user_id, c.is_overlap
FROM over_lap c

UNION ALL

-- Get users without overlaps
SELECT s3.user_id, 0 AS is_overlap
FROM subscriptions s3
WHERE NOT EXISTS (
    SELECT 1 
    FROM over_lap ol 
    WHERE ol.user_id = s3.user_id
);

Leave a Reply

Your email address will not be published. Required fields are marked *

Deprecated: htmlspecialchars(): Passing null to parameter #1 ($string) of type string is deprecated in /var/www/html/wp-includes/formatting.php on line 4720