Top N Rows for Each Group in SQL
In SQL, selecting the top rows for each group can be accomplished using window functions. Window functions allow for calculations to be performed on a set of rows, known as a window, that are defined by a specified ordering and partition. In this case, we want to select the top two rows for each group, which can be achieved using the following steps:
Here is an example query implementing these steps:
SELECT * FROM ( SELECT *, RANK() OVER (PARTITION BY NAME ORDER BY SCORE DESC) AS row_rank FROM test ) AS ranked WHERE row_rank <= 2
This query will produce the desired output, as shown below:
NAME SCORE ----------------- willy 2 willy 3 zoe 5 zoe 6
The above is the detailed content of How to Select the Top N Rows for Each Group in SQL?. For more information, please follow other related articles on the PHP Chinese website!