gpt4 book ai didi

MySQL-聚合函数的滥用

转载 作者:行者123 更新时间:2023-11-29 10:15:04 25 4
gpt4 key购买 nike

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

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 中做错了什么?

最佳答案

可能是这样的:

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)

关于MySQL-聚合函数的滥用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50235704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com