使用GROUP BY

时间:2015-08-18 13:49:26

标签: mysql select group-by having

我有一些表:

name    dep_id  salary
Vasia   5       1000
Oleg    5       1300
Vitia   4       1000
Sacha   3       1100
Kolia   5       1600
Lesha   2       1400
Sergey  4       1200
Marina  5       1300
Olga    5       1500
Igor    4       1400
Valia   3       1500
Erema   4       1500

我需要获得部门中name最多salary的员工{/ 1}}

即我需要

 Lesha   1400
 Valia   1500
 Erema   1500
 Kolia   1600

我试过了:

SELECT name, max(salary) FROM employees GROUP BY dep_id

但显示的值不正确

我该怎么做?

3 个答案:

答案 0 :(得分:3)

select e1.*
from employees e1
join
(
  SELECT dep_id, max(salary) as msal
  FROM employees
  GROUP BY dep_id
) e2 on e1.dep_id = e2.dep_id
    and e1.salary = e2.msal

答案 1 :(得分:1)

select t1.name,t2.sallary
from Employees t1 join
     (select dep_id,MAX(Sallary) as Sallary
      from Employees
      group by dep_id) t2 on t1.dep_id=t2.dep_id and t1.sallary=t2.sallary
order by t2.sallary

结果:

name    Sallary
---------------
Lesha   1400
Valia   1500
Erema   1500
Kolia   1600

SQL Fiddle

中的演示

答案 2 :(得分:0)

尝试以下查询以获取所需的输出:

    select name,sallary from employees t1 where (dep_id,sallary) in
    (select dep_id,max(sallary) from employees group by dep_id);