嗨,我有以下代码,我在其中尝试获取飞机ID(aircraftid)以及其服务的次数(count(serviceid)),但仅在count(serviceid)大于平均计数(服务ID)。
select aircraftid, s.times
from(
select aircraftid, count(serviceid) as times
from service
group by aircraftid
) as s
having times > avg(times);
但是当我运行它时,它不返回任何行
当我将代码更改为
select aircraftid, s.times
from(
select aircraftid, count(serviceid) as times
from service
group by aircraftid
) as s
having times > 2;
它返回行
答案 0 :(得分:0)
您可以试试这个-
SELECT aircraftid,
COUNT(serviceid) AS times
FROM service
GROUP BY aircraftid
HAVING COUNT(serviceid) > (
SELECT AVG(T) FROM
(
SELECT count(serviceid) T
FROM service
GROUP BY aircraftid
)A
)
答案 1 :(得分:0)
您需要对avg子查询进行交叉联接
select aircraftid, s.times
from(
select aircraftid, count(serviceid) as times
from service
group by aircraftid
) as s
cross join (
select avg(times) avg_time
from (
select aircraftid, count(serviceid) as times
from service
group by aircraftid
) t
) t2
where s.times > t2.avg_time
或在haveing子句中使用子查询,因为您需要在select中选择aircraftid列,但不在..组中,而您需要总体平均值。
答案 2 :(得分:0)
我建议使用窗口功能:
select aircraftid, s.times
from (select aircraftid, count(*) as times,
avg(count(*)) over () as avg_times
from service
group by aircraftid
) s
where times > avg_times;
Window函数是MySQL 8中引入的,是解决此问题的最佳方法。