在MS SQL Server中为每个类别返回5个最新文章

时间:2011-03-18 19:31:05

标签: sql-server sql-server-2008

假设我在SQL Server 2008数据库上有一个表Articles,其列为ID INT, Title VARCHAR(100), CatID INT, Posted DATETIME

要获取特定类别的5篇最新文章,我可以这样做。

SELECT TOP (5) * FROM Articles WHERE CatID = @CatID ORDER BY Posted DESC

但如果我想要每个类别的5篇最新文章怎么办?我知道我可以为每个类别重复上面的查询,但有没有办法做一个单独的查询,将返回每个类别的5篇最新文章?

修改

这是我用来返回带有@SectionID部分的5篇最新文章的实际查询。根据我正在使用的实际术语,它是我所分组的“部分”,而不是“类别”。

SELECT TOP (5) *
FROM Article
    INNER JOIN Subcategory on Article.ArtSubcategoryID = Subcategory.SubID
    INNER JOIN Category on Subcategory.SubCatID = Category.CatID
    INNER JOIN section ON Category.CatSectionID = Section.SecID
WHERE (Section.SecID = @SectionID)
ORDER BY Article.ArtUpdated DESC

编辑2:

这是我根据这里的评论提出的查询。似乎工作正常。

SELECT  *
FROM (
    SELECT Article.*,
        ROW_NUMBER() OVER (PARTITION BY SecID ORDER BY ArtUpdated DESC) AS rn
    FROM Article
        INNER JOIN Subcategory on Article.ArtSubcategoryID = Subcategory.SubID
        INNER JOIN Category on Subcategory.SubCatID = Category.CatID
        INNER JOIN section ON Category.CatSectionID = Section.SecID
) q
WHERE rn <= 5

2 个答案:

答案 0 :(得分:4)

SELECT  *
FROM    (
        SELECT  *,
                ROW_NUMBER() OVER (PARTITION BY CatId ORDER BY Posted DESC) AS rn
        FROM    Articles
        ) q
WHERE   rn <= 5

答案 1 :(得分:3)

试试这个

;WITH CTE AS (SELECT ROW_NUMBER() OVER(PARTITION BY CatID ORDER BY Posted DESC) 
AS Rownum,*
FROM Articles )

SELECT * FROM CTE WHERE Rownum <= 5