当前位置:网站首页>[SQL] sql19 finds the last of all employees_ Name and first_ Name and corresponding Dept_ name

[SQL] sql19 finds the last of all employees_ Name and first_ Name and corresponding Dept_ name

2022-04-21 12:24:00 A research monk who doesn't like research

subject :

Find all employees last_name and first_name And corresponding dept_name_ Niuke Tiba _ Cattle from

There's an employee list employees A brief introduction is as follows :

emp_no birth_date first_name last_name gender hire_date
10001 1953-09-02 Georgi Facello M 1986-06-26
10002 1964-06-02 Bezalel Simmel F 1985-11-21
10003 1959-12-03 Parto Bamford M 1986-08-28
10004 1954-05-01 Chirstian Koblick M 1986-12-01

There is a department table departments The table is summarized as follows :

dept_no dept_name
d001 Marketing
d002 Finance
d003 Human Resources

There is one , Department employee relations form dept_emp A brief introduction is as follows :

emp_no dept_no from_date to_date
10001 d001 1986-06-26 9999-01-01
10002 d001 1996-08-03 9999-01-01
10003 d002 1990-08-05 9999-01-01

Please find the of all employees last_name and first_name And corresponding dept_name, It also includes employees who have no assigned department for the time being , The output of the above example is as follows :

last_name first_name dept_name
Facello Georgi Marketing
Simmel Bezalel Marketing
Bamford Parto Finance
Koblick Chirstian NULL

Answer key :

Because employees without assigned department should also display , So take the employee table employees Subject to , You must output all the lines inside , Use it twice left join To connect three tables , The second time left join Is the last time left join The resulting temporary table is the same as the third table join.

select
    e.last_name,
    e.first_name,
    ds.dept_name
from
    employees e
left join
    dept_emp dp
on
    e.emp_no = dp.emp_no
left join
    departments ds
on
    dp.dept_no = ds.dept_no

版权声明
本文为[A research monk who doesn't like research]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204211131571526.html