Saturday, 18 October 2014

Self Joins in SQL Server

Self Joins in SQL Server- Find the Manager Name for each employee in the employee table
self join is a join of a table to itself. This table appears twice in the FROM clause and is followed by table aliases that qualify column names in the join condition. To perform a self join, Oracle combines and returns rows of the table that satisfy the join condition.
For example the following query returns employee names and their manager names for whom they are working.
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);
Select * from Emp;



select e.empid,e.name,m.name as 'mgr name' from Emp e, Emp m where e.mgrid =m.empid
select e.empid,e.name,m.name as 'mgr name' from Emp e, Emp m where m.empid = e.mgrid



Fetch the Managers
SELECT DISTINCT e1.EmpId, e1.name FROM Emp e1, Emp e2 where e1.EmpId=e2.mgrid; 


Fetch the Employee who has Managers
SELECT DISTINCT e2.EmpId, e2.name FROM Emp e1, Emp e2 where e1.EmpId=e2.mgrid; 





Thanks
~ Suraj K.

0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives