获得前 10 个 post 和每个 post sql 的 10 个评论
get top 10 posts and 10 comments for each post sql
我想根据分数获得前 10 post,每个 post 获得 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 个 post,但问题是它获得了此 post 的所有评论。如何修改此查询以使每个 post?
仅获得 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
, 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
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
试试这个:
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
我想根据分数获得前 10 post,每个 post 获得 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 个 post,但问题是它获得了此 post 的所有评论。如何修改此查询以使每个 post?
仅获得 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
, 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
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
试试这个:
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