download

Why does joining payments and tickets inflate revenue?

SQL~9 minReviewed 2 Dec 2026Free · No sign-in

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_idamount_cents
1500
1500
2900

tickets

ticket_idaccount_id
711
721
731
743
Show hints (2)
  1. "COUNT THE COMBINATIONS"

    For account 1, every payment can pair with every ticket.

  2. "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.

"SOLUTION · SQL"
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;
"OUTPUT"
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 →

Original OfferVibe question. SQLite SELECT · SQLite aggregate functions.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.