Why does joining payments and tickets inflate revenue?
Question
Report every account's payment total and support ticket count. Keep accounts with no activity. The two tables can have several rows per account. Explain how joining them directly can inflate the sums and counts. Sort by account ID.
accounts
| account_id |
|---|
| 1 |
| 2 |
| 3 |
payments
| account_id | amount_cents |
|---|---|
| 1 | 500 |
| 1 | 500 |
| 2 | 900 |
tickets
| ticket_id | account_id |
|---|---|
| 71 | 1 |
| 72 | 1 |
| 73 | 1 |
| 74 | 3 |
Show hints (2)
- "COUNT THE COMBINATIONS"
For account 1, every payment can pair with every ticket.
- "GROUP EACH SIDE FIRST"
Build one row per account in each child table before joining either to accounts.
Show checked explanation
Aggregate payments and tickets separately by account. Left join those two summaries to accounts and use zero when a summary is missing.
WITH payment_totals AS ( SELECT account_id, SUM(amount_cents) AS paid_cents FROM payments GROUP BY account_id ), ticket_counts AS ( SELECT account_id, COUNT(*) AS tickets FROM tickets GROUP BY account_id ) SELECT a.account_id, COALESCE(p.paid_cents, 0) AS paid_cents, COALESCE(t.tickets, 0) AS tickets FROM accounts AS a LEFT JOIN payment_totals AS p ON p.account_id = a.account_id LEFT JOIN ticket_counts AS t ON t.account_id = a.account_id ORDER BY a.account_id;
account_id | paid_cents | tickets 1 | 1000 | 3 2 | 900 | 0 3 | 0 | 1
Ran the query on SQLite 3.49 with the sample rows and edge cases.
Walkthrough
Account 1 has two payments and three tickets. Joining raw rows produces six pairs for that account. Each payment appears three times, inflating the sum to 3000 cents. Aggregating each table first leaves at most one row per account on each side.
Common mistakes
- Joining both raw tables and grouping only at the end.
- Using
SUM(DISTINCT amount_cents). The two valid 500-cent payments would become one. - Using inner joins and losing accounts with activity on just one side.
Follow-up questions
- "Would COUNT(DISTINCT ticket_id) fix the whole result?" It can fix the ticket count when IDs are unique. The payment sum still repeats each payment across tickets.
- "What if the report needs a row per account per month?" Aggregate both fact tables at account and month before joining. Use the same keys for the resulting joins and decide which account-months the report should include.
What a strong answer covers
Identify the row grain on each side and explain how you prevent the one-to-many joins from multiplying each other.
Open in interactive practice deck →