Select top 10 records for each category

前端 未结 14 1162
别那么骄傲
别那么骄傲 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:29

    I do it this way:

    SELECT a.* FROM articles AS a
      LEFT JOIN articles AS a2 
        ON a.section = a2.section AND a.article_date <= a2.article_date
    GROUP BY a.article_id
    HAVING COUNT(*) <= 10;
    

    update: This example of GROUP BY works in MySQL and SQLite only, because those databases are more permissive than standard SQL regarding GROUP BY. Most SQL implementations require that all columns in the select-list that aren't part of an aggregate expression are also in the GROUP BY.

    0 讨论(0)
  • 2020-11-22 05:30

    Might the UNION operator work for you? Have one SELECT for each section, then UNION them together. Guess it would only work for a fixed number of sections though.

    0 讨论(0)
提交回复
热议问题