Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 获取子查询SQL的平均值_Mysql_Sql - Fatal编程技术网

Mysql 获取子查询SQL的平均值

Mysql 获取子查询SQL的平均值,mysql,sql,Mysql,Sql,您好,我有下面的代码,我试图获取飞机ID(aircraftid)和它们被服务的次数(计数(serviceid)),但仅当计数(serviceid)大于平均计数(serviceid)时才显示它们 但当我运行它时,它不会返回任何行 当我将代码更改为 select aircraftid, s.times from( select aircraftid, count(serviceid) as times from service group by aircraftid ) as s having ti

您好,我有下面的代码,我试图获取飞机ID(aircraftid)和它们被服务的次数(计数(serviceid)),但仅当计数(serviceid)大于平均计数(serviceid)时才显示它们

但当我运行它时,它不会返回任何行

当我将代码更改为

select aircraftid, s.times
from(
select aircraftid, count(serviceid) as times
from service
group by aircraftid
) as s
having times > 2;
它返回行

您可以试试这个-

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
)

在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 

或者在having子句中使用子查询,因为您需要select中的aircraftid列,但它不在group by..中,并且您需要总体平均值..

我建议使用窗口功能:

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;
MySQL 8中引入了窗口函数,是解决此问题的最佳方法

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;