自我加入SQL

时间:2016-06-27 10:26:01

标签: sql

我有一张包含少量记录的员工表,我希望从中获得在员工“scott”工作的部门工作的所有员工以及部门编号为20的员工。

3 个答案:

答案 0 :(得分:0)

您可以尝试以下查询,并告诉我这是否适用于您

select * from employee where deptno in (select deptno from employee where name ='scott')

答案 1 :(得分:0)

不是很具描述性,但你可以根据你提供的信息尝试这个,

Create Table #Employees
(Id int,
EmpName nvarchar(20),
Deptno int
)

Insert into #Employees Values(1,'Henry',10)
Insert into #Employees Values(2,'Mark',20)
Insert into #Employees Values(3,'Scott',20)
Insert into #Employees Values(4,'David',10)
Insert into #Employees Values(5,'Peter',30)
Insert into #Employees Values(6,'Mary',20)
Insert into #Employees Values(7,'John',30)


Select EmpName From #Employees
Where Deptno In(Select Deptno from #Employees Where EmpName = 'Scott')
  

有关员工的完整信息,

  Select * From #Employees
  Where Deptno In(Select Deptno from #Employees Where EmpName = 'Scott')

答案 2 :(得分:0)

例如,以下查询返回其工作对象的员工姓名及其经理姓名。复制&粘贴下面的sql,我认为这可能有助于达到目的。

Create table Emp
(

empid int primary key,
name varchar(50),
mgrid int
)

Insert into Emp(empid,name,mgrid)

values (1001,'Manish Agrahari',1001); 

Insert into Emp(empid,name,mgrid)values (1002,'Deepti',1001);

Insert into Emp(empid,name,mgrid)values (1003,'Amit',1001);

Insert into Emp(empid,name,mgrid)values (1004,'Sandy',1002);

Insert into Emp(empid,name,mgrid)values (1005,'Ankit',1003);

Insert into Emp(empid,name,mgrid)values (1006,'Kapil',1002);

运行以下SQL并查看结果:

SELECT e.empid, e.name, m.name  "Manager" FROM Emp e, Emp m WHERE e.mgrid=m.empid;