简单SQL查询返回空值

时间:2019-11-22 15:56:27

标签: mysql sql database

我刚刚开始研究SQL查询。 我正在以下站点上练习:https://www.techonthenet.com/sql/joins_try_sql.php

我想找到:

  

“每个部门薪水最高的员工的姓名”。

我的查询是:

SELECT first_name, max(salary) FROM employees, departments 
WHERE departments.dept_id=employees.dept_id
GROUP BY employees.dept_id

我得到first_name的空值: query result 我知道问题是由于group by表达式引起的。但是我该如何解决呢?

表格: query result

4 个答案:

答案 0 :(得分:3)

尝试一下:

SELECT e.first_name, e.salary FROM employees as e
INNER JOIN departments as d ON d.dept_id=e.dept_id
WHERE e.salary IN (SELECT max(salary) FROM employees GROUP BY dept_id)

答案 1 :(得分:1)

您也可以像下面一样使用row_number(),除非需要显示部门名称,否则无需加入部门表:

Select e.*
from employees e
INNER JOIN
(
   SELECT e.id, e.dept_id. e.first_name, 
          rn=row_number() over (partition by e.dept_id order by e.salary desc)
   FROM employees e 
) x ON x.id = e.id
where x.rn = 1

编辑

(由于OP不想使用row_number()函数amd,结果查询将在mysql中而不是sql server中使用)->您可以尝试以下方法:

select em.*
from employees em, (
    Select dept_id, max(salary) salary
    from employees e
    group by dept_id
) x on x.dept_id=em.dept_id and x.salary = em.salary

应该可以,但是据我所知,在线编译器不接受带有子查询的联接。在这种情况下,我想到的最简单的解决方案:

select em.*
from employees em
where salary = (select max(salary) from employees em2 where em.dept_id = em2.dept_id)

答案 2 :(得分:1)

SELECT top 2 first_name,max(salary) FROM employees, departments
WHERE departments.dept_id=employees.dept_id

GROUP BY first_name
order by max(salary) desc

答案 3 :(得分:0)

尝试一下:

select first_name, b.dept_id, salary  from employees a,
(
SELECT employees.dept_id, max(salary) as salary FROM employees, departments 
WHERE departments.dept_id=employees.dept_id
GROUP BY employees.dept_id
 )b where a.salary = b.salary and a.dept_id= b.dept_id