Write SQL using HAVING and window functions
PayPalData Scientist · Technical ScreenLast updated
This question tests the ability to filter aggregated data using the HAVING clause and compute relative metrics using window functions to identify high-frequency transaction patterns.
Fraud Detection Analytics
You are working with a transactions table that logs payments made by users. Your goal is to identify "high-activity" users who have demonstrated potential risk.
Schema
Table transactions:
user_id: INTamount: DECIMALtransaction_time: TIMESTAMP
Requirements
- Identify users who have completed more than 5 transactions in total.
- For these users, calculate their "transaction rank" for each day based on the amount spent (highest amount = rank 1). If two transactions have the same amount, assign them the same rank and skip the next rank (e.g., 1, 2, 2, 4).
- Return a table containing
user_id,transaction_time,amount, and the calculatedday_rank.
Constraints
- Use standard SQL syntax (PostgreSQL/BigQuery compatible).
- Ensure the filter for "more than 5 transactions" is applied before or during the result generation.
Example
Input:
| user_id | amount | transaction_time |
|---|---|---|
| 1 | 100 | 2023-01-01 10:00:00 |
| 1 | 200 | 2023-01-01 11:00:00 |
| 1 | 100 | 2023-01-01 12:00:00 |
Output (if user 1 had > 5 total transactions):
| user_id | transaction_time | amount | day_rank |
|---|---|---|---|
| 1 | 2023-01-01 10:00:00 | 100 | 2 |
| 1 | 2023-01-01 11:00:00 | 200 | 1 |
| 1 | 2023-01-01 12:00:00 | 100 | 2 |
Hints
Hint 1
Use a subquery or a Common Table Expression (CTE) with a GROUP BY and HAVING count(*) > 5 clause to filter the list of active users.
Hint 2
Use the DENSE_RANK() window function partition by user_id and the date portion of the timestamp to calculate the daily ranking.
Hint 3
Ensure the final query joins your list of high-activity users back to the original transaction table to fetch the specific records.
Follow-up questions
- How would your query change if you needed to identify the top 3 transactions per user per day regardless of their total transaction count?
- What are the performance implications of using a window function on a table with 100 million rows compared to a self-join approach?
- How would you modify the ranking logic to use a dense rank if multiple transactions on the same day had identical amounts?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.