简体   繁体   English

简单的 SQL 查询返回 null 值

[英]Simple SQL query returning null value

I just started studying SQL queries.我刚开始研究 SQL 查询。 I am practicing on this site: https://www.techonthenet.com/sql/joins_try_sql.php我在这个网站上练习: https://www.techonthenet.com/sql/joins_try_sql.php

I want to find:我想找到:

"the name of the employee with the highest salary for every department". “每个部门工资最高的员工的名字”。

My query is:我的查询是:

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

And I get null value for first_name :我得到了first_name的 null 值: 查询结果 I understand that the problem is due to the group by expressions.我知道问题是由于group by表达式。 But how can I solve this?但是我该如何解决呢?

Tables:表: 查询结果

You can alternatively use row_number() like below, you don't need to join to departments table unless you need to show the name of the department:您也可以像下面这样使用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

EDIT编辑

(Since OP does not want to use row_number() function amd it turned out the query will be used in mysql instead of sql server) -> Can you please try this: (由于 OP 不想使用 row_number() function 和结果,查询将在 mysql 中使用,而不是 sql 服务器)-> 你可以试试这个

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

That should work but the online compiler does not accept join with a sub-query as far as I understand.这应该可以,但据我所知,在线编译器不接受子查询的加入。 Easiest solution I can think of, in this case:在这种情况下,我能想到的最简单的解决方案:

select em.*
from employees em
where salary = (select max(salary) from employees em2 where em.dept_id = em2.dept_id)
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

try this:尝试这个:

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)

Try this:尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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