Skip to content Skip to sidebar Skip to footer

Sql Grouping - Show Only 5 Comments Per Post

To make thing easier to understand lets take the following example: I want to show only the top 5 comments for a specific post (Like the post on facebook where people cant comment

Solution 1:

select
   *
FROM
   tblPost P
   OUTER APPLY
   (SELECT TOP 5 * FROM tblComment C  
      WHERE P.id = C.postid
      ORDER BY something) inline

Solution 2:

Try using ROW_NUMBER, assuming you are using a database that supports it:

SELECT id, postid
FROM tblComment
(
    SELECT 
        id,
        postid,
        ROW_NUMBER() OVER (PARTITION BY postid ORDER BY id DESC) AS rn
    FROM tblComment
) AS T1
WHERE rn <= 5

Post a Comment for "Sql Grouping - Show Only 5 Comments Per Post"