Detailed explanation of MySQL group sorting to find the top N

Detailed explanation of MySQL group sorting to find the top N

MySQL group sorting to find the top N

Table Structure


Group by grp, sort by num, and take the top 3 in each group. The output is as follows:




source code:

SELECT * FROM score AS t3  
WHERE (  
  SELECT COUNT(*) FROM score AS t1  
  LEFT JOIN score AS t2  
  ON t1.grp = t2.grp AND t1.num < t2.num  
  WHERE t1.id = t3.id 
) < 3 
ORDER BY t3.grp ASC, num DESC 
 

In where, you can create a new variable for filtering through a subquery.

Thank you for reading, I hope it can help you, thank you for your support of this site!

You may also be interested in:
  • Mysql uses group by group sorting
  • Detailed explanation of the implementation principle of MySQL group query Group By
  • Implement group by based on MySQL to get the latest data of each group
  • How to use GROUP BY in MySQL to get the first N records
  • Detailed explanation of the implementation example of group ranking in Mysql tutorial

<<:  React+Koa example of implementing file upload

>>:  How to build Jenkins+Maven+Git continuous integration environment on CentOS7

Recommend

MySQL replication table details and example code

MySQL replication table detailed explanation If w...

Analysis of the process of building a LAN server based on http.server

I don’t know if you have ever encountered such a ...

mysql solves the problem of finding records where two or more fields are NULL

Core code /*-------------------------------- Find...

Example code of how to create a collapsed header effect using only CSS

Collapsed headers are a great solution for displa...

Solution to multiple 302 responses in nginx proxy (nginx Follow 302)

Proxying multiple 302s with proxy_intercept_error...

Markup Language - Phrase Elements

Click here to return to the 123WORDPRESS.COM HTML ...

Detailed steps to build the TypeScript environment and deploy it to VSCode

Table of contents TypeScript environment construc...

Summary of Node.js service Docker container application practice

This article will not explain the use and install...

Examples of correct use of interface and type methods in TypeScript

Table of contents Preface interface type Appendix...

The viewport in the meta tag controls the device screen css

Copy code The code is as follows: <meta name=&...

5 Tips for Protecting Your MySQL Data Warehouse

Aggregating data from various sources allows the ...