Click here to Skip to main content
15,911,139 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
I have to retrieve employee, reporting manager and senior reporting manager

SQL
select
		HR2.EmployeeName as Employee_Name,
		HR1.EmployeeName as Reporting_Manager,
		HR3.EmployeeName as Seniour_Reporting_Manager
from 
		HR HR1, HR HR2, HR HR3
where 
		HR1.EmployeeName= HR2.ReportingManagerName
	 and 
                HR1.ReportingManagerName = HR3.EmployeeName
order by 
		HR2.EmployeeName 


but it retriving the data as

Employee_Name|Reporting_Manager|Seniour_Reporting_Manager
-------------|-----------------|---------------------------
abc          |def              |ghi
scd          |asd              |qwe


the value is coming correctly

but i need the reporting mamger to come in same column
like

Employee_Name|Reporting_Manager
-------------|------------------
abc          |def              
abc          |ghi       


thank you
Posted
Updated 19-Nov-13 18:43pm
v2

If I understood you correctly you have a homework assignment related to the recursive queries[^]. If you follow the link you will find the example that uses exactly the same model (employee->manager).

To adapt the query to your example the result will look something like this:
;WITH DirectReports (EmployeeName, EmployeeManager, Level)
AS
(
-- Anchor member definition
    SELECT e.EmployeeName, 0 AS Level
    FROM HR AS e
    WHERE e.ReportingManagerName IS NULL
    UNION ALL
-- Recursive member definition
    SELECT e.EmployeeName, 
        Level + 1
    FROM HR AS e
    INNER JOIN DirectReports AS d
        ON e.ReportingManagerName = e.EmployeeName
)
-- Statement that executes the CTE
SELECT EmployeeName, EmployeeManager, Level
FROM DirectReports
ORDER BY EmployeeName;
 
Share this answer
 
v2
Comments
write2varun 20-Nov-13 1:02am    
Can it be done without using CTE
I just need a Query to put in the stored procedure to retrieve the data in a new table
This query solved my problem

SQL
declare  @Reporties table (EmployeeName varchar(50), Reporting_Manager varchar(50))

insert @Reporties (EmployeeName,Reporting_Manager)(
    SELECT H.EmployeeName, H.ReportingManagerName
    FROM HR AS H
    UNION ALL
   select HR2.EmployeeName,HR3.EmployeeName
from 
		HR HR1, HR HR2, HR HR3
where 
		HR1.EmployeeName= HR2.ReportingManagerName
	and HR1.ReportingManagerName = HR3.EmployeeName
)
SELECT distinct EmployeeName, Reporting_Manager
FROM @Reporties
ORDER BY EmployeeName
 
Share this answer
 

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