← Window functions

Top 2 by number of purchases in a country: web, Apr 2025

Level: Middle100 XP

Instructions

For users with platform = 'web' compute total, the number of their purchases with purchased_at on or after April 1, 2025 and strictly before May 1, 2025 (only users who had such purchases). In each country (users.country), number the users with ROW_NUMBER() by total descending, for equal total by user id ascending. Output the users with rn <= 2 in each country: country, user_id, total and rn (the number). Row order does not matter.

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

events.user_id (0…N) ↔ users.id (1…1)purchases.user_id (0…N) ↔ users.id (1…1)eventsPKidintegerFKuser_idintegerpurchasesPKidintegerFKuser_idintegerusersPKidinteger
Exactly oneZero or oneZero or more
Table relationships
  • N:1Many-to-oneevents.user_id → users.id
  • N:1Many-to-onepurchases.user_id → users.id

Table data

PostgreSQL

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

Dataset schema