连接 2 个表中的数据

发布于 2024-12-08 02:43:47 字数 670 浏览 0 评论 0原文

我正在研究 Adventureworks 示例数据库。

我有一张有员工的桌子,都有一位特定的经理。所以在表employee's 中有一个列ManagerID。

另外,在雇员表中还有一个 ContactID,其中包含该雇员的姓名。

我想要一份包含所有经理及其姓名的名单。我怎样才能做到这一点?

该表看起来像这样

EmployeeID  ContactID  ManagerID
----------  ---------  ---------
    1           21         4
    2           24         4
    3           32         7
    4           34         2
    5           35         2
    6           42         7
    7           44         4

,所以我需要一个不同的 managerID 列表,然后搜索每个 managerID 及其适当的 ContactID。

所以: 员工 1 的经理是员工 4,ContactID 为 34。 员工 3 的经理是员工 7,ContactID 为 44。 员工 4 的经理是员工 2,ContactID 为 24。

谢谢。

I'm working on the adventureworks example database.

I have a table with employee's, which all have a certain manager. So in the table employee's there is a column ManagerID.

Also in the table employee there's a ContactID, which contains the name of that employee.

I would like to have a list with all the managers and their names. How can I pull this off?

The table looks something like

EmployeeID  ContactID  ManagerID
----------  ---------  ---------
    1           21         4
    2           24         4
    3           32         7
    4           34         2
    5           35         2
    6           42         7
    7           44         4

So i'll need a DISTINCT list of the managerID, and then search for each managerID their appropreate ContactID.

So:
manager of employee 1 is Employee 4 with the ContactID 34.
manager of employee 3 is Employee 7 with the ContactID 44.
manager of employee 4 is Employee 2 with the ContactID 24.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

肥爪爪 2024-12-15 02:43:47

您可以将表 myTable 与本身匹配的 manager_id 和 employee_id 结合起来

select 
    t.employeeid as employee_id, 
    t.manager_id as manager_id, 
    t2.contact_id as manager_contact_id 
from mytable t left outer join mytable t2 on t.managerid = t2.employeeid

You can do it joining the table myTable with itself matching manager_id's with employee_id's

select 
    t.employeeid as employee_id, 
    t.manager_id as manager_id, 
    t2.contact_id as manager_contact_id 
from mytable t left outer join mytable t2 on t.managerid = t2.employeeid
暖伴 2024-12-15 02:43:47
SELECT ManagerID, EmployeeID, ConactID
FROM ´yourtable´
GROUP BY ManagerID

在那里您可以获得分组数据。
如果您还想列出经理,则必须再次加入数据(自加入)

SELECT ManagerID, EmployeeID, ConactID
FROM ´yourtable´
GROUP BY ManagerID

There you get the grouped data.
If you want to have Managers listed as well you have to JOIN the data again (self-join)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文