Skip to content

Instantly share code, notes, and snippets.

@ncalm
Created May 29, 2024 20:34
Show Gist options
  • Save ncalm/60424593fb696dc2165aa64d07496341 to your computer and use it in GitHub Desktop.
Save ncalm/60424593fb696dc2165aa64d07496341 to your computer and use it in GitHub Desktop.
T-SQL solution for a question of "Find users for whom each booking is within 7 days of their most recent booking"
-- https://medium.com/@mail2asimmanna/another-beautiful-sql-question-from-my-business-analyst-interview-1d9fa00c0381
DROP TABLE IF EXISTS #bookings;
SELECT
CAST(u AS smallint) AS userid,
CAST(d AS date) AS booking_date
INTO #bookings
FROM
(VALUES (1,'2024-01-01')
,(1,'2024-01-03')
,(1,'2024-01-09')
,(2,'2024-01-10')
,(2,'2024-01-18')
,(2,'2024-01-20')
,(3,'2024-01-10')
,(3,'2024-01-19')
,(3,'2024-01-30')
,(4,'2024-01-05')
,(4,'2024-01-09')
,(4,'2024-01-11')
,(4,'2024-01-19')) AS t(u, d);
--SELECT DISTINCT
-- SQL_VARIANT_PROPERTY(
-- CONVERT(sql_variant, booking_date),
-- 'BaseType'
-- ) AS type_of_booking_date
--FROM #bookings;
WITH dat
AS (
SELECT
userid,
booking_date,
DATEDIFF(
DAY,
LAG(booking_date) OVER (PARTITION BY userid ORDER BY booking_date),
booking_date
) AS diff
FROM #bookings
)
SELECT userid AS frequent_user_userid
FROM dat
EXCEPT
SELECT userid
FROM dat
WHERE diff > 7;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment