Select top 10 records for each category

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

    I know this thread is a little bit old but I've just bumped into a similar problem (select the newest article from each category) and this is the solution I came up with :

    WITH [TopCategoryArticles] AS (
        SELECT 
            [ArticleID],
            ROW_NUMBER() OVER (
                PARTITION BY [ArticleCategoryID]
                ORDER BY [ArticleDate] DESC
            ) AS [Order]
        FROM [dbo].[Articles]
    )
    SELECT [Articles].* 
    FROM 
        [TopCategoryArticles] LEFT JOIN 
        [dbo].[Articles] ON
            [TopCategoryArticles].[ArticleID] = [Articles].[ArticleID]
    WHERE [TopCategoryArticles].[Order] = 1
    

    This is very similar to Darrel's solution but overcomes the RANK problem that might return more rows than intended.

提交回复
热议问题