Table Schema
Inspect
Table
| Column | Type |
|---|---|
| txn_id | integer |
| user_id | integer |
| amount | decimal |
| txn_time | datetime |
| device_id | varchar |
Find users who made more than 3 transactions within 1 minute.
Table Schema
| Column | Type |
|---|---|
| txn_id | integer |
| user_id | integer |
| amount | decimal |
| txn_time | datetime |
| device_id | varchar |
Sample Data
| txn_id | user_id | amount | txn_time | device_id |
|---|---|---|---|---|
| 1 | 101 | 100 | 10:00:00 | A |
| 2 | 101 | 200 | 10:00:20 | A |
| 3 | 101 | 150 | 10:00:40 | A |
| 4 | 101 | 300 | 10:00:50 | A |
| 5 | 102 | 500 | 11:00:00 | B |
| 6 | 102 | 600 | 11:05:00 | B |
| 7 | 103 | 200 | 12:00:00 | C |
| user_id |
|---|
| 101 |
SQL Editor
| user_id |
|---|
| 101 |
Hints
Solution
Solution is locked until you decide to reveal it. Try the editor first, then open this when you want the reference answer.
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 t1.txn_time + INTERVAL '1 minute' GROUP BY t1.user_id, t1.txn_id, t1.txn_time HAVING COUNT(*) > 3;
Explanation
Self-join transactions by user.
Limit the joined rows to a 1 minute window.
Return users with more than 3 transactions in any such window.
Related Questions