max(count(*))错误:单组组功能

时间:2014-05-07 02:01:14

标签: sql database oracle group-by oracle10g

假设我有两个表:

  1. 用户
    enter image description here
  2. 销售
    enter image description here
  3. 我需要更改此查询:显示购买软件副本的前三名用户
    我的SQL是这样的:

    select u.name, u.age, u.sex, u.email, s.selluid, max(count(u.uid)) FROM users u, sells s where u.usrid = s.selluid
    

    有关如何解决此问题的任何想法?感谢

3 个答案:

答案 0 :(得分:1)

SELECT x.*
FROM (
       SELECT u.name
            , u.age
            , u.sex
            , u.email
            , s.selluid
            , COUNT(*) as t 
       FROM users u JOIN sells s ON u.usrid = s.selluid
       GROUP BY u.name
       ORDER BY COUNT(*) DESC
     ) x 
 WHERE ROWNUM <= 3

答案 1 :(得分:1)

试试这个

select u.usrid, u.name, count(s.sellid) 
from users u left join sells s on u.usrid=s.selluid 
group by u.usrid, u.name order by count(s.sellid) desc;

答案 2 :(得分:1)

您可以使用带有row_number()的聚合子查询来解决此问题:

select u.*, s.numsales
from users u join
     (select s.selluid, count(*) as numsales,
             row_number() over (order by count(*) desc) as seqnum
      from sells s
      group by s.selluid
     ) s
     on u.userid = s.selluid
where seqnum <= 3;

这种方法的一个优点是,您可以使用users轻松获取u.*中的所有列。