我一直在尝试运行以下命令:
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
中做错了什么?
答案 0 :(得分:1)
这样的事情可能是:
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)