【问题标题】:Return an employee's first + lastname and their manager's first + last name返回员工的名字 + 姓氏及其经理的名字 + 姓氏
【发布时间】:2021-07-22 05:34:16
【问题描述】:

我正在尝试在 SQL 中编写一个查询,以从同一个“员工”表中返回员工的名字 + 姓氏和他们经理的名字 + 姓氏。每个员工都有一个employeeid 和一个包含其经理的employeeid 的“reportsto”列。

这是我到目前为止返回的第一部分(员工的名字 + 姓氏和报告对象的 ID)

SELECT employee.employeeid, employee.firstname, employee.lastname, employee.reportsto
FROM employee
WHERE employee.reportsto IS NOT NULL;

返回

 employeeid | firstname | lastname | reportsto
------------+-----------+----------+-----------
          2 | Nancy     | Edwards  |         1
          3 | Jane      | Peacock  |         2
          4 | Margaret  | Park     |         2
          5 | Steve     | Johnson  |         2
          6 | Michael   | Mitchell |         1
          7 | Robert    | King     |         6
          8 | Laura     | Callahan |         6

我不知道如何获取“reportsto”,获取它对应的employeeid,然后添加经理员工的名字+姓氏并将其添加到同一记录中。

所以表格应该是“employeeid, firstname, lastname, managerFirstName, managerLastName”

任何帮助将不胜感激。

【问题讨论】:

  • 做一个self join,即employee e join employee m。也许左加入。

标签: sql postgresql


【解决方案1】:

做一个self join来获得经理的名字。

SELECT e.employeeid, e.firstname, e.lastname,
       m.firstname managerFirstName, m.lastname managerLastName
FROM employee e
JOIN employee m ON e.reportsto = m.employeeid 
WHERE e.reportsto IS NOT NULL;

【讨论】:

    猜你喜欢
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多