帮助SQL查询

时间:2011-02-28 08:43:53

标签: sql

我有以下表格博客(id)和帖子(id,blog_id,comment_count) 我需要从不同的博客中选择五篇评论最多的帖子。使用函数很容易,但是可以使用某种基本的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

2 个答案:

答案 0 :(得分: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)

更新希望这就是您所需要的。但它并不是很快。

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;

答案 1 :(得分:0)

据我所知,没有标准的方法来实现主要dbms实际支持的Select Top

请参阅comparison of SQL dialects