Select top 10 records for each category

前端 未结 14 1354
别那么骄傲
别那么骄傲 2020-11-22 04:27

I want to return top 10 records from each section in one query. Can anyone help with how to do it? Section is one of the columns in the table.

Database is SQL Serve

14条回答
  •  日久生厌
    2020-11-22 05:23

    You can try this approach. This query returns 10 most populated cities for each country.

       SELECT city, country, population
       FROM
       (SELECT city, country, population, 
       @country_rank := IF(@current_country = country, @country_rank + 1, 1) AS country_rank,
       @current_country := country 
       FROM cities
       ORDER BY country, population DESC
       ) ranked
       WHERE country_rank <= 10;
    

提交回复
热议问题