在sql中使用Group by进行查询

时间:2013-06-12 19:21:52

标签: sql oracle

我有下表:

ReviewID | Author_id | Posted time
-------------------------------------
R1       | U1        | ...
R2       | U2
R3       | U2
R9       | U7
R11      | U7 
R12      | U7
R13      | U8
R14      | U10

我的查询是这样的,我想得到U7。我尝试了以下内容:

 select author_id 
 from posted_reviews_tab 
 group by author_id
 having (count(author_id)) in (
        select max(count(author_id)) 
        from posted_reviews_tab   
        where reviewid in ( 
             select w.reviews.reviewid 
             from wall_tab w  
             where w.shopid = 'S9' 
        ) 
        group by author_id
);    

shop s9有4条评论R11,R12,R13,R14在它的墙上。上表显示哪个用户发布了哪个评论。从我的墙桌上,我开始知道哪个商店的所有评论都写在墙上。所以,一旦我得到所有的评论,我想找出发布了大量评论的用户(这是U7) 上面的查询给了我U2,因为最大计数是2.(2个becoz u7发布在R11和R12之后)任何人都可以推荐一个解决方法吗?

2 个答案:

答案 0 :(得分:0)

据我了解这个问题,这就是你想要的......

select author_id from posted_reviews_tab group by author_id
 having (count(author_id)) in (

 select max(author_id) from posted_reviews_tab   
 where reviewid in ( 
 select w.reviews.reviewid from wall_tab w  where w.shopid = 'S9' 
 ) 
 group by author_id
  ); 

答案 1 :(得分:0)

这可以让你获得U7,但我不确定我是否理解你要求将结果限制在特定商店的要求。

select author_id,
       cnt
from (
   select author_id, 
          count(*) cnt,
          rank() over (order by count(*) desc) as rnk
   from posted_reviews_tab
   group by author_id
) t
where rnk = 1;

SQLFiddle示例:http://sqlfiddle.com/#!4/52d62/1