Real-world recipes · Sales and marketing

Top 3 in every group

In Excel, you'd reach for
fxSort by region then sales, and eyeball the top of each block

"Best-selling products in each region" is a classic. ROW_NUMBER() OVER (PARTITION BY region ORDER BY units DESC) numbers rows 1, 2, 3... separately inside each region. Then keep rows numbered 3 or less.

Try itEdit the query, then Run
regionrank_in_regionproductunits
Asia Pacific1Desk Lamp131
Asia Pacific2Noise-Cancel Headset75
Asia Pacific3Gel Pens (10)70
Europe1Desk Lamp129
Europe2Notebook Pack65
Europe3Gel Pens (10)53
Latin America1Desk Lamp118
Latin America2Notebook Pack80
Latin America3Webcam HD61
North America1Desk Lamp129

Showing 10 of 12 rows. Press Run to see them all.

PARTITION BY is "restart the numbering for each…". Without it, you'd get one ranking across all regions.

Your turn

For each country, find the customer who signed up first. Show country, name and signup_date.

This page on one card

Top 3 in every group: the Excel way (Sort by region then sales) and the SQL query, side by side
Top 3 in every group, on one card: the Excel way and the SQL. Download · Save to Pinterest
The practice data (7 tables)

See every column and sample rows