Select top n rows from each group sql

A Top N query is one that fetches the top records, ordered by some value, in descending order. Typically, these are accomplished using the TOP or LIMIT clause. Problem is, Top N result sets are limited to the highest values in the table, without any grouping. The GROUP BY clause can help with that, but it is limited to the single top result for each group. If you want the top 5 per category, GROUP BY won't help by itself. That doesn't mean it can't be done. In fact, in today's blog, we'll learn exactly how to construct a Top N query by group.

Top N Query Basics

To gain a better understanding of a the Top N Query, let's compose one that selects the top 5 films with the longest running times from the Sakila Sample Database. If you aren't familiar with the Sakila database, it's a MySQL database that contains a number of tables, views, and queries related to a fictional video rental store. Tables include actor, film, customer, rentals, etc.

Select top n rows from each group sql

Grouping Results by Category

The GROUP BY clause applies an aggregate function to one or more fields so that the data relates to the groupings that you specify. It's a step forward in terms of grouping results, but GROUP BY still has a couple of limitations:

  • it only provides the very first result (i.e. row) per group and ignores others,
  • the columns are limited to those included in the grouping criteria and aggregated field(s). All other columns are not accessible.

This query uses GROUP BY to show the longest running film for each rating:

Select top n rows from each group sql

Notice that we can't include the film title title, because it is not part of either the GROUP BY or aggregated field(s).

Crash Course in Windows Functions

The term "window" in Windows Functions refers to the set of rows on which the function operates because the function uses values from the rows in a window to calculate the returned values. The set of rows within the window are aggregated into a single value.

To use a window function in a query, you have to define the window using the OVER() clause. It does 2 things:

  1. Defines window partitions to form groups of rows, via the PARTITION BY clause.
  2. Orders rows within a partition, via the ORDER BY clause.

A query can include multiple window functions with the same or different window definitions.

Our query uses the ROW_NUMBER() window function. It assigns a sequential integer number to each row in the query's inner window result set. We can use that value to limit the results for each rating to the top 5. That's done by ordering the length in descending order.

Select top n rows from each group sql

Conclusion

In today's blog we learned how to construct a query that fetches the top 5 rows per category in Navicat Premium. Version 15 adds over 100 enhancements and includes several new features to give you more ways that ever to build, manage, and maintain your databases than ever before!

Sometimes you may need to select top N rows from each group in MySQL. Here’s how to select top N rows per group in MySQL. You can use it to get top n results per group, select top 10 record for each category or select first record of each group.

Here are the steps to select top N rows per group. Let’s say you have the following table orders(id, product, amount)

mysql> create table product_orders(id int,product varchar(255),amount int); mysql> insert into product_orders(id, product, amount)

 values(1,'A',250),(2,'B',150),(3,'C',200),
 (4,'A',250),(5,'B',210),(6,'C',125),
 (7,'A',350),(8,'B',225),(9,'C',150);
mysql> select * from product_orders; ++---++

id product amount
+------+---------+--------+
1 A 250
2 B 150
3 C 200
4 A 250
5 B 210
6 C 125
7 A 350
8 B 225
9 C 150
+------+---------+--------+

Bonus Read : How to Get Last Week Data in MySQL

How to Select Top N Rows Per Group in MySQL

First, we will rank each row within its group (product column) using the following SQL query.

mysql> SELECT id, product, amount,

        @product_rank := IF(@current_product = product, @product_rank + 1, 1) 
         AS product_rank,
        @current_product := product
   FROM product_orders
   ORDER BY product, amount desc;
++---++--+-----+

id product amount product_rank @current_product := product
+------+---------+--------+--------------+-----------------------------+
7 A 350 1 A
1 A 250 2 A
4 A 250 3 A
8 B 225 1 B
5 B 210 2 B
2 B 150 3 B
3 C 200 1 C
9 C 150 2 C
6 C 125 3 C
+------+---------+--------+--------------+-----------------------------+

In the above query, we have first sorted each record within its group by amount column in descending order, and then ranked it. If you want to sort it in ascending order of amounts, you can do it by changing the ORDER by clause.

SELECT id, product, amount,

   @product_rank := IF(@current_product = product, @product_rank + 1, 1) 
   AS product_rank,
   @current_product := product 
FROM product_orders ORDER BY product, amount asc;

Next, we use the above query as a subquery, to select top N rows per group (e.g top 2 rows for each category).

Bonus Read : MySQL Copy Database

How to select top 2 rows per group

Here’s the SQL query to select top 2 rows for each group using the above method. We will use the above query as subquery and select rows whose rank is less than or equal to 2.

How do I SELECT top n rows for each group in SQL?

Getting the top-N rows for a group is a two-step process:.

Assign row numbers starting at one for each group..

Filter the result of this down to the rows less than or equal to the number you want..

How do you SELECT the top row from each group in SQL Server?

The GROUP BY Statement in SQL is used to arrange identical data into groups with the help of some functions. To select the first row of each group in SQL, you can use the ' GROUP BY ' clause with the ' MIN ' or ' MAX ' aggregate function.

How do you retrieve the top n records from a table in SQL?

TOP (top_value): It Returns the top n number of records in the result set based on top_value. For example, TOP(10) in the select query will return the top 10 records from the full result set.

How do I SELECT one row from each group in postgresql?

Use the Postgres' “SELECT DISTINCT ON” statement to select one row per group. The stated statement selects and retrieves a random row from each group.