简体   繁体   中英

MYSQL top 2 salaried employees in each department and average department salary

MySQL, top 2 salaried employees in each department and average department salary. I was able to retrive the top two salaried employees in each department with, but i dont know how to inlude average department salary

SELECT *
FROM Employee e1
WHERE 2 > (
           SELECT COUNT(DISTINCT Salary)
           FROM Employee e2
           WHERE e2.Salary > e1.Salary
           AND e1.Dept = e2.Dept
        );

I'm fairly new at sql myself but I don't think you would be able to include the average by department in the same query. Your where statement will have an effect on your selection therefore any average you queried would only be the average of the rows returned by the where statement. It would seem to me (again in my limited experience) that a second query would have to be made to render the average salaries using something like

SELECT AVG(e1.salary),  AVG(e2.salary), DISTINCT e1.dept, DISTINCT e2.dept

FROM Employee e1 GROUP BY e1.dept, e2.dept

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM