Write a SQL query that returns the most recent successful transaction for each customer using a ROW_NUMBER() window function.
💡 Model Answer
Here’s a concise query that returns the most recent successful transaction for each customer using a ROW_NUMBER window function: WITH ranked_transactions AS ( SELECT customer_id, amount, status, transaction_date, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY transaction_date DESC) AS rn FROM transactions WHERE status = 'success' ) SELECT customer_id, amount, transaction_date FROM ranked_transactions WHERE rn = 1; The CTE ranks transactions per customer by date, assigning 1 to the newest. The outer query then filters to those rows. This approach is efficient because the window function is computed once per partition, and the final filter is a simple equality check. If you need to include additional columns or handle ties, you can adjust the ORDER BY clause or use RANK() instead of ROW_NUMBER().
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500