Click here to Skip to main content
15,887,822 members
Please Sign up or sign in to vote.
3.00/5 (3 votes)
Hi,

how to write a query to get the out put


Emp_id     EMP_name   Manger_id

  1          kiran     Null
  2          stephen    1
  3          Basha      2
  4          surya      3



and i want the out put as

Emp_name    Manager Name
kiran         Null
stephen      kiran
 Basha      stephen
 surya       Basha
Posted
Updated 27-May-11 2:30am
v2
Comments
Sergey Alexandrovich Kryukov 24-May-11 16:53pm    
What's the hierarchy..! Do any of these employers have any time to work? :-)
--SA
sairam.bhat 25-May-11 2:44am    
good qstn
sairam.bhat 25-May-11 2:44am    
my +5

SQL
DECLARE @tmp as Table(ID int,EmpName varchar(10),ManagerID int)
INSERT INTO @tmp  SELECT 1,'Kiran',null
INSERT INTO @tmp  SELECT 2,'Stephen',1
INSERT INTO @tmp  SELECT 3,'Basha',2
INSERT INTO @tmp  SELECT 4,'Surya',3

SELECT
    t1.*,
    t2.EmpName ManagerName
FROM @tmp t1
    LEFT JOIN @tmp t2
ON  t1.ManagerID = t2.ID
 
Share this answer
 
Comments
cid_moossaa 3-Nov-11 0:17am    
simple but effective
Start here[^] - it's easier than it looks once you get going.
 
Share this answer
 
Comments
sairam.bhat 25-May-11 2:44am    
good ans my +5
Use SELF JOIN[^]
 
Share this answer
 
Comments
sairam.bhat 25-May-11 2:45am    
good ans my +5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900