← Aggregates, GROUP BY and HAVING

Top 3 merchants by spending, from 1000 per purchase

Level: Junior50 XP

Instructions

Among the expenses (amount at most -1000) with a merchant set (merchant is not NULL) made on or after March 1, 2025 and strictly before July 1, 2025, compute by merchant: tx_cnt, the number of transactions, and spent, the total spending as a positive number (minus the sum of amount). Select merchant, tx_cnt, spent and keep the 3 merchants with the highest spending. Sort by spent descending; for equal spending, by merchant ascending.

Hints

Each next one is more detailed and costs more

Log in to open hints

Query

Result

Click Run to see the query result, or Check to submit your solution.

Dataset schema

accounts.client_id (0…N) ↔ clients.id (1…1)transactions.account_id (0…N) ↔ accounts.id (1…1)accountsPKidintegerFKclient_idintegerclientsPKidintegertransactionsPKidintegerFKaccount_idinteger
Exactly oneZero or oneZero or more
Table relationships
  • N:1Many-to-oneaccounts.client_id → clients.id
  • N:1Many-to-onetransactions.account_id → accounts.id

Table data

PostgreSQL

Select a table in the diagram or list to view its rows.

Dataset schema