2011-02-28 252 views
1

我有以下表博客(ID)和帖子(ID,blog_id,comment_count) 我需要從不同的博客中選擇五個最多評論的職位。使用函數很容易,但是可以使用某種基本的SQL嗎?幫助SQL查詢

下面是在SQL Server方言

select top 5 top_post.* from Blogs b 
cross apply 
    (select top 1 * from Posts p 
    where p.blog_id = b.id 
    order by p.comment_count) top_post 
order by top_post.comment_count 
+0

實際上,您需要5個博客,並且我認爲有頂級評論文章嗎? – 2011-02-28 09:21:05

回答

0
SELECT b.*, c.num_comments 
FROM 
(
    SELECT TOP 5 blog_id, SUM(comment_count) as num_comments 
    FROM posts GROUP BY blog_id ORDER BY SUM(comment_count) DESC 
)c 
INNER JOIN Blogs b ON (b.id = c.blog_id) 

UPDATE查詢希望這是你所需要的。雖然它不是很快。

SELECT b.*, c.comment_count 
FROM 
(SELECT blog_id, comment_count , 
ROW_NUMBER() OVER(PARTITION by blog_id ORDER BY comment_count DESC) as rnum 
FROM posts 
)c 
INNER JOIN Blogs b ON (b.id = c.blog_id) 
WHERE c.rnum <=5; 
+0

這將獲得大多數評論博客,但我需要職位。 – synapse 2011-02-28 09:29:39

+0

因此,每個博客最多需要5個帖子,對吧? – a1ex07 2011-02-28 09:32:33

+0

我需要5個帖子。 – synapse 2011-02-28 09:41:24