如何在SQL中使用group by时返回多个列

时间:2011-08-03 17:28:11

标签: mysql sql

我想要员工的姓名以及最高工资低于50,000的工资和部门。我有以下

SELECT department, MAX(salary) as Highest salary
FROM employees
GROUP BY department
HAVING MAX(salary) < 50000

如何获取要退回的员工的姓名?

2 个答案:

答案 0 :(得分:10)

如此接近......

SELECT department, name, MAX(salary) as Highest salary
FROM employees
GROUP BY department, name
HAVING MAX(salary) < 50000

评论更新后

SELECT name, department , salary
FROM employees e
   JOIN
  (
    SELECT department as dept, MAX(salary) as HighestSalary
    FROM employees
    GROUP BY department
  ) MaxE ON e.department = MaxE.dept AND e.salary = MaxE.HighestSalary

答案 1 :(得分:5)

除非我误解了要求,否则只需将员工添加到选择/组中?

SELECT employee, department, MAX(salary) as Highest salary
FROM employees
GROUP BY employee, department
HAVING MAX(salary) < 50000