Write SQL for Transactions and Customers
Company: Affirm
Role: Data Engineer
Category: Data Manipulation (SQL/Python)
Difficulty: Medium
Interview Round: Technical Screen
You are given two tables:
- customers(customer_id INT PRIMARY KEY, signup_date DATE, region VARCHAR, segment VARCHAR)
- transactions(transaction_id INT PRIMARY KEY, customer_id INT, amount DECIMAL(10,
2), status VARCHAR, transaction_ts TIMESTAMP)
Assume status = 'SUCCESS' indicates a completed purchase.
Write SQL to answer the following:
1) Using a CTE, compute for the last three full calendar months the total successful revenue and number of active customers per region (an active customer has at least one successful transaction in that month). Return month (YYYY-MM), region, revenue, active_customers, and also rank regions by revenue within each month using a window function.
2) For each customer, return their top three successful transactions by amount. Break ties by earlier transaction_ts. Output customer_id, transaction_id, amount, transaction_ts, and the per-customer rank (use a window function).
3) Using a CTE and window functions, compute the average number of days between consecutive successful transactions per customer, then aggregate to the segment level over the past 180 days. Return segment, customers_covered, and avg_gap_days.
Quick Answer: This question evaluates proficiency with SQL CTEs, window functions, aggregation, per-group top-N queries, and time-based analytics on transactional and customer data.