Joins Deep Dive
Explore how to accurately calculate monthly revenue per active user using SQL joins. Understand the importance of maintaining data granularity to prevent duplications that inflate revenue. Learn techniques to validate join results, handle unmatched rows with LEFT JOIN, and apply correct join conditions including self joins and full outer joins. This lesson teaches how to detect and correct common join errors that affect revenue and user activity analysis in data science interviews.
The interviewer asks, “Calculate monthly revenue per active user.” This lesson uses three tables: users, with one row per user; orders, with one row per order and columns for user_id, amount, and created_at; and events, which records user activity. An incorrect approach joins orders to events on user_id, groups the results by month, and divides SUM(o.amount) by the number of active users. The join matches records by user_id but can duplicate order rows when a user has multiple events, inflating the revenue total. If a user has one $30 order and two matching January events, the join produces two rows containing the same order amount, causing that order to contribute $60 to the revenue total. Starting from orders and using an INNER JOIN with events also excludes active users who have no matching orders, potentially understating the active-user denominator.
The resulting calculation error may not be immediately apparent. January revenue totals $60 across two active users, resulting in $30 in revenue per active user. The joined query incorrectly reports $60 per active user because each order matches two event rows, doubling the aggregated revenue from $60 to $120. Because SUM() includes the duplicated order amounts, the query returns an inflated metric without producing a SQL execution error.
An effective approach calculates revenue and active-user counts separately. The orders table contains revenue data at the order level, with one row per order_id. Deduplicate the events table to obtain one row per active user_id per month. Aggregate each dataset to the appropriate monthly granularity before joining, or calculate revenue and active-user counts separately and join the monthly results.
Lines 55–69: The join matches each order to every event the same user generated in the same ...