How to find maximum avg

前端 未结 15 2168
长情又很酷
长情又很酷 2020-12-15 19:17

I am trying to display the maximum average salary; however, I can\'t seem to get it to work.

I can get a list of the average salaries to display with:



        
相关标签:
15条回答
  • 2020-12-15 19:58
    select worker_id, avgsal 
    from 
    (
      select worker_id, avg(salary) as avgsal 
      from workers 
      group by worker_id
    ) 
    where avgsal=(select  max(avgsal) 
                  from (select worker_id, avg(salary) as avgsal 
                        from workers group by worker_id))
    

    This will display the highest average along with worker id

    0 讨论(0)
  • 2020-12-15 19:58
    select worker_id, avg(salary)
    from workers
    group by worker_id
    having avg(salary) = (select max(avgsal) from 
    (select worker_id, avg(salary) as avgsal 
    from workers 
    group by worker_id));
    

    This should also work i guess

    0 讨论(0)
  • 2020-12-15 19:59

    As explained here you can use

    SELECT worker_id, AVG(salary)
    FROM workers
    GROUP BY worker_id
    HAVING AVG(salary) = (SELECT MAX(AVG(salary)) FROM workers GROUP BY worker_id) 
    
    0 讨论(0)
  • 2020-12-15 19:59

    https://stackoverflow.com/a/8050885/12190487 shows the folllowing error

    ER_DERIVED_MUST_HAVE_ALIAS: Every derived table must have its own alias
    

    Use alias for the new formed column you are selecting from

    select max(avg_salary)
    from (select worker_id, avg(salary) AS avg_salary
          from workers
          group by worker_id) as avg ; 
    
    0 讨论(0)
  • 2020-12-15 19:59

    You can also do this with a single select statement (combining both max and avg) like this

    select max(avg(salary)) max_avg_salary
    from workers
    group by worker_id;
    
    0 讨论(0)
  • 2020-12-15 20:00

    Columns resulting from aggregate functions (e.g. avg) usually get arbitrary names. Just use an alias for it, and select on that:

    select max(avg_salary)
    from (select worker_id, avg(salary) AS avg_salary
          from workers
          group by worker_id) As maxSalary;
    
    0 讨论(0)
提交回复
热议问题