聚合函数误用

6ss1mwsb  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(292)

我一直在尝试运行以下命令:

select s.name, s.nr
from sub s
group by s.name
having (select count(s.name) from sub s group by s.name) > 
10 * (select avg(count(s.name)) from sub s group by s.name)

以获得所有用户的姓名和电话号码,这些用户的通话次数是每个用户平均通话次数的10倍以上。
我到底做错了什么 select avg(count(s.name)) from sub s group by s.name ?

5cg8jx4n

5cg8jx4n1#

可能是这样的:

select s.name, s.nr
from sub s
group by s.name, s.nr
having count(*) > 10 * (
    select avg(cnt)
    from (
        select count(*) as cnt
        from sub
        group by name, nr
     )x

还可以通过单个(非嵌套)子查询获取平均计数:

select count(*) / count(distinct name, nr) from sub

读作:所有行的数目/不同组的数目-这是每个组的平均行数。
因此,您的完整查询将是:

select s.name, s.nr
from sub s
group by s.name, s.nr
having count(*) > 10 * (select count(*) / count(distinct name, nr) from sub)

相关问题