每个帖子sql获得前10个帖子和10条评论

时间:2015-03-18 15:17:45

标签: sql sql-server tsql sql-server-2012

我希望根据得分获得前10名帖子,并为每个帖子获得10条评论。 我使用以下查询:

with a as ( SELECt TOP 10  Score,Post.ID as PostID 
FROM            Post 
order by Score desc ), b as
(select  PostID,ID as CommentID from PostComment) 
select * from a
left join b
on b.PostID = a.PostID

此查询获得前10个帖子,但问题是它获得了此帖子的所有评论。如何修改此查询以获得每篇帖子只有10条评论?

3 个答案:

答案 0 :(得分:4)

这些方面的东西都可行。

with a as 
(
    SELECt TOP 10  Score
    , Post.ID as PostID 
    FROM Post 
    order by Score desc 
), b as
(
    select PostID
    , ID as CommentID 
    , ROW_NUMBER() over (partition by PostID order by ID) as RowNum
    from PostComment
) 
select * 
from a
left join b
on b.PostID = a.PostID
where b.RowNum <= 10

答案 1 :(得分:2)

试试这个:

WITH a AS ( 
    SELECT TOP 10
        Score ,
        Post.ID AS PostID
    FROM Post
    ORDER BY Score DESC
)
SELECT  *
FROM    a
OUTER APPLY ( 
    SELECT TOP 10
        pc.PostID ,
        pc.ID AS CommentID
    FROM      PostComment pc
    WHERE     pc.PostID = a.PostID
    --ORDER BY SomeColumn
) o

答案 2 :(得分:1)

SELECT
    *
FROM
    (
      SELECT
        Score ,
        Post.ID AS PostID ,
        ROW_NUMBER() OVER ( PARTITION BY p.id ) row_num ,
        comms.*
      FROM
        Post p
        OUTER APPLY (
                      SELECT TOP 10
                        pc.Comment_PostID ,
                        pc.ID AS CommentID
                      FROM
                        PostComment pc
                      WHERE
                        pc.postid = p.id
                    ) comms
    ) a
WHERE
    row_num < 11
相关问题