Menu

How to get top n results in each ‘group by’ group in SQL?

Let's see how to get top n results in each 'group by' group in SQL. You have a table with multiple records. For each distinct value in each 'group by' group, get the top 'n' rows based on some criteria

Written by Selva Prabhakaran | 2 min read

Problem

You have a table with multiple records. For each distinct value in one of the columns (i.e., each ‘group by’ group), you want to retrieve the top ‘n’ rows based on some criteria.

In the below example, get the top 2 entries for each sales person based on ‘amount’ column.

Input

idsalespersonamountsale_date
1John100.002023-09-10
2John200.002023-09-15
3John50.002023-09-18
4Jane150.002023-09-11
5Jane300.002023-09-14
6Doe400.002023-09-10
7Doe100.002023-09-16

Try Hands-On: Fiddle

Create Input Table: Gist

Desired Output

salespersonamountsale_date
Doe400.002023-09-10
Doe100.002023-09-16
Jane300.002023-09-14
Jane150.002023-09-11
John200.002023-09-15
John100.002023-09-10

Solution 1:

Using Window Functions

sql
    WITH RankedSales AS (
        SELECT
            salesperson,
            amount,
            sale_date,
            ROW_NUMBER() OVER(PARTITION BY salesperson ORDER BY amount DESC) AS rn
        FROM sales
    )

    SELECT salesperson, amount, sale_date
    FROM RankedSales
    WHERE rn <= 2;

Explanation:

ROW_NUMBER() OVER(PARTITION BY salesperson ORDER BY amount DESC) – This assigns a unique sequential integer to rows within a partition of a result set.

We use a Common Table Expression (CTE) namedRankedSales to make our main query simpler.

In the main query, we filter out the results to only include rows where the row number (rn) is 2 or les
ns.

Solution 2:

Using Correlated sub query

sql
SELECT s1.salesperson, s1.amount, s1.sale_date
FROM sales s1
WHERE (
    SELECT COUNT(*) 
    FROM sales s2 
    WHERE s1.salesperson = s2.salesperson AND s2.amount >= s1.amount
) <= 2
ORDER BY s1.salesperson, s1.amoun DESC;

Explanation:

The outer query iterates over each row in the sales table aliasing it as s1.

The inner query (correlated subquery) counts how many records have an amount greater than or equal to the current record for the same salesperson.

The condition of <= 2 in the outer query is used to limit the results to only the top 2 sales for each salesperson.

The main drawback of this method is that the correlated subquery will execute for each row in the sales table, which could be inefficient for larger datasets.

Still, this method provides a way to achieve the desired result without relying on window functions or session variables, making it useful in certain scenarios or older versions of databases that don’t support more advanced features.

  1. SQL for Data Science – Level 1
  2. SQL for Data Science – Level 2
  3. SQL for Data Science – Level 3
  1. Introduction to SQL
  2. SQL Window Functons – Made Simple and Easy
  3. SQL Subquery

More SQL Questions

  1. How to concatenate multiple rows into one field in SQL?
  2. How to efficiently convert rows to columns in SQL?
  3. How to transpose columns to rows in SQL?
  4. How to select first row in each GROUP BY group?
Free Course
Master Core Python — Your First Step into AI/ML

Build a strong Python foundation with hands-on exercises designed for aspiring Data Scientists and AI/ML Engineers.

Start Free Course
Trusted by 50,000+ learners
Related Course
Master SQL — Hands-On
Join 5,000+ students at edu.machinelearningplus.com
Explore Course
Machine Learning Plus
MachineLearningPlus Expert AI/ML Training

Get a Free 30-Min
Guidance Call

Let our ML expert call you back and guide you for free

You're all set!
Tired of tutorials that go nowhere? This video shows you why and what to do instead.
Watch the Free Training
Redirecting in 5 seconds...
No thanks, I'll figure it out myself

Get your Start in AI/ML with the Foundations for Data Science (AI/ML) Course

Enroll for Free
Scroll to Top
Scroll to Top
Course Preview

Machine Learning A-Z™: Hands-On Python & R In Data Science

Free Sample Videos:

Machine Learning A-Z™: Hands-On Python & R In Data Science

Machine Learning A-Z™: Hands-On Python & R In Data Science

Machine Learning A-Z™: Hands-On Python & R In Data Science

Machine Learning A-Z™: Hands-On Python & R In Data Science

Machine Learning A-Z™: Hands-On Python & R In Data Science