Subqueries and CTEs · Problem 64 of 118

Accounts with Many Transactions

MediumSubqueries and CTEsBank data

Count the transactions of every account. Return account_id and txns for the five accounts with the most transactions among those whose count is above the average count (average over all accounts). Sort by txns from high to low, then account_id.

Hint 1

Count per account in a CTE, then compare each count with the average of the counts.

Reference solution

WITH counts AS (
  SELECT account_id, COUNT(*) AS txns
  FROM transactions
  GROUP BY account_id
)
SELECT account_id, txns
FROM counts
WHERE txns > (SELECT AVG(txns) FROM counts)
ORDER BY txns DESC, account_id
LIMIT 5;

The same two-step shape as the previous problem: summarise, then compare with a summary of the summary. Recognising this shape quickly is a big part of fluency: "above average", "more than the typical", "better than most" all become "aggregate per group, then a scalar subquery over that result".