create table [company](companyid int,empname varchar(150), teamleadid int)
insert into [company] values(1,'Kalyan',3)
insert into [company] values(2,'shiva',1)
insert into [company](companyid,empname) values(3,'sai')
insert into [company] values(4,'vijendhar',1)
insert into [company] values(5,'sandeep',1)
select * from [company]
Now the result will be as follows.
From the above we need fetch the data as follows.
To get the data as above we need to use SELF JOIN as follows.
select e.empname as employee, t.empname as teamleader
from company e
left join company t
on e.teamleadid= t.companyid
Where employee Sai do not have any team leader, so the following are the ways to remove the null value and instead of that we need to place the name TRUMP.
By using ISNULL()
select e.empname as employee, isnull(t.empname,'TRUMP') as teamleader
from company e
left join company t
on e.teamleadid= t.companyid
By using CASE statement.
select e.empname as employee, CASE WHEN t.empname is null THEN 'TRUMP' ELSE t.empname END as teamleader
from company e
left join company t
on e.teamleadid= t.companyid
By using COALESCE() function
select e.empname as employee, COALESCE(t.empname, 'TRUMP' ) as teamleader
from company e
left join company t
on e.teamleadid= t.companyid
No comments:
Post a Comment