⏱️ TIME-BASED SQL QUERIES (CODING + LOGIC) 1️⃣ Find Users with N Transactions in X Minutes 🔥 MOST ASKED QUESTION Table: transactions(user_id, txn_id, amount, txn_time) ✅ Requirement Find users with ≥ 3 transactions in 10 minutes SELECT DISTINCT t1.user_id FROM transactions t1 JOIN transactions t2 ON t1.user_id = t2.user_id AND t2.txn_time BETWEEN t1.txn_time AND DATEADD( MINUTE , 10 , t1.txn_time) GROUP BY t1.user_id, t1.txn_time HAVING COUNT ( * ) >= 3 ; 🗣 Explain “This uses a rolling time window using a self-join. Very common in fraud detection.” 2️⃣ Consecutive Days / Events 🔥 Login, sales, activity streak questions Table: logins(user_id, login_date) ✅ Find users with 3 consecutive login days WITH cte AS ( SELECT user_id, login_date, DATEADD( DAY , - ROW_NUMBER() OVER ( PARTITION BY user_id ORDER BY login_date ), login_date ) grp FR...
Comments
Post a Comment