Home > Database > Mysql Tutorial > How to Select the Top Two Rows for Each Group in SQL?

How to Select the Top Two Rows for Each Group in SQL?

Mary-Kate Olsen
Release: 2024-12-31 15:13:13
Original
570 people have browsed it

How to Select the Top Two Rows for Each Group in SQL?

Selecting the Top Two Rows in Each SQL Group

In SQL, a common task is to retrieve only the top rows for each group. However, the standard aggregation functions for grouping (such as MAX() and MIN()) only allow for the selection of the highest or lowest value.

Query for Selecting the Top Two Scores per Name:

To address this challenge, a more complex query is required. Here's an example of how to select the top two scores for each name in the table provided:

SELECT *
FROM   test s
WHERE 
        (
            SELECT  COUNT(*) 
            FROM    test  f
            WHERE f.name = s.name AND 
                  f.score >= s.score
        ) <= 2;
Copy after login

Explanation:

  • The outer query (SELECT * ...) retrieves all rows from the test table.
  • The subquery (SELECT COUNT(*) ...) determines how many records exist for each name in the test table with a score equal to or greater than the current row's score.
  • The WHERE clause then filters the rows in the outer query by ensuring that the count from the subquery is less than or equal to 2.

Example Output:

The query above returns the following output:

NAME    SCORE
-----------------
willy       2
willy       3
zoe         5
zoe         6
Copy after login

This output includes the top two scores for each name in the table, as requested.

The above is the detailed content of How to Select the Top Two Rows for Each Group in SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template