Get the App
SLTechnology News&Howtos  ›  Database  › 

Example Analysis of getting topN by GROUP BY grouping sort in MySQL

Shulou Source: shulou.com Published: 2022-05-31 15:57:08 10月01日 Update

This article mainly introduces the example analysis of getting topN by GROUP BY grouping sorting in MySQL. The article is very detailed and has a certain reference value. Interested friends must read it!

MySQL VERSION: 5.5.45

ENGINE: InnoDB

Problem description:

Get the record of each student's top n in the transcript.

Table structure:

Table data:

Method 1 (user variable):

①, first of all, I get all the results of each group's ranking.

Click (here) to collapse or open

Select @ gp_row:=if (@ name=name,@gp_row+1,1) as gp_row,@name:=name,id,name,grade from td, (select @ gp_row:=0,@name:='') as temp order by name,grade desc

The results are as follows:

② is using the result as an intermediate table to query the data of top N.

Click (here) to collapse or open

Select id,name,grade from (select @ gp_row:=if (@ name=name,@gp_row+1,1) as gp_row,@name:=name,id,name,grade from td, (select @ gp_row:=0,@name:='') as temp order by name,grade desc) as tb_gp_rank where gp_rowa.grade)

Tags: Results queries fields data grouping sorting scores indexes examples analysis content situation method article structure that is value interest again Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Shulou Information Xiaomi Shulou Technology Apple