【问题标题】:Joining data from 2 tables连接来自 2 个表的数据
【发布时间】:2011-10-05 11:54:42
【问题描述】:

我正在开发 Adventureworks 示例数据库。

我有一张员工的桌子,都有一位经理。所以在表employee中有一列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。

谢谢。

【问题讨论】:

    标签: sql sql-server join


    【解决方案1】:

    您可以加入表 myTable 并使其自身匹配 manager_id's 和 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
    

    【讨论】:

      【解决方案2】:
      SELECT ManagerID, EmployeeID, ConactID
      FROM ´yourtable´
      GROUP BY ManagerID
      

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

      【讨论】:

      • 这仍然给出了员工的 ContactID,而不是它的经理
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-11
      • 1970-01-01
      • 2019-03-09
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多