我需要sql查询来合并来自2个表的信息

时间:2014-01-30 22:38:49

标签: sql sql-server

我是SQL的新手,我需要一个提示。我有两张桌子(员工和部门),

员工表格为E: id(int),name(nvarchar),gender(nvarchar),departmentID(int),dateofbirth(datetime) 部门表为D: dep_id(int),name(nvarchar),location(nvarchar),boss_id(int)

这就是我需要的输出表:

E.id / E.name / D.name / D.location /(最后我无法通过简单的连接获得:) D.boss.name(不是简单的老板ID,而是来自E表的真实员工姓名)

对于高级人士来说只是一个简单的问题: - )

3 个答案:

答案 0 :(得分:2)

第二次为老板加入桌子。 (假设boss_id FK为Employee

SELECT
    E.Id,
    E.Name,
    D.Name,
    D.Location,
    B.Name
FROM Employee E
    INNER JOIN Department D on E.DepartmentID = D.Dep_id
    INNER JOIN Employee B ON D.Boss_id = B.Id

答案 1 :(得分:0)

您也可以使用cte编写查询:

WITH CTE AS(
Select 
e.ID,
e.name,
d.boss_id,
d.Location as DepartmentLocation,
d.name as DepartmentName
From Employee e
INNER JOIN Department d on d.boss_id =E.id
)
Select c.id, c.name, e.name as BossName, c.DepartmentLocation, c.DepartmentName

from cte c 
Inner Join Employee e1 on e1.id=c.boss_id

答案 2 :(得分:-1)

SELECT e.Id, e.Name, d.Name, d.Location,
(
SELECT e2.Name
FROM tblEmployee as e2
WHERE e2.id = d.boss_id
) AS [Boss name]
FROM tblEmployee as e 
INNER JOIN tblDepartment as d
ON e.DepartmentID = d.dep_ID