Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Need help for getting reporting hierarchy

Author  Topic 

Christine_Brown
Starting Member

2 Posts

Posted - 2009-10-14 : 04:16:22
Hi

I have a Job table and a Name table which are having the following fields

Job Table
---------------
Emplid Supervisor_ID
1 5
2 4
3 5
4 7
5 4
6 5
7 8
8 NULL

Name table
-----------

Emplid Name_display
1 Antony
2 Maria
3 Jose
4 Camelia
5 Susan
6 Sandra
7 Matts
8 NULL

How to i write a query to get

1.Emplid
2.Employee Name
3.Supervisor ID
4.Supervisor Name
5.Manager ID(Supervisor`s Supervisor)
6.Manager Name
7.Approver ID(Manager`s Supervisor)
8.Approver NAme


Any help is greatly appreciated

Thanks,
Christine

Lumbago
Norsk Yak Master

3271 Posts

Posted - 2009-10-14 : 05:31:48
This looks like a cut'n'paste from some school assignment or whatever so unless you post some efforts yourself I'm only gonna point you in the right direction: look up "recursive cte" (recursive common table expression) in Books Online or here at the forum...it will do what you need to do.

- Lumbago
http://xkcd.com/327/
Go to Top of Page

Christine_Brown
Starting Member

2 Posts

Posted - 2009-10-14 : 08:38:14
Lumbago :This is not a school assignment.And for your info CTE is only good for storing values temporarily.
Go to Top of Page

Lumbago
Norsk Yak Master

3271 Posts

Posted - 2009-10-15 : 04:56:02
It doesn't really matter if it's a school assignment or whatever else it is, but it's always good courtesy to make an effort yourself before asking for solutions. We are in the teaching/learning-business here, not the doing-work-for-others business . And you're partly right that the CTE might not be the best solution for your exact requirement since you want the "recursiveness" in columns instead of rows, but for YOUR info a CTE is useful for a lot more than "storing values temporarily", which is not a very accurate way of describing a CTE btw (http://msdn.microsoft.com/en-us/library/ms190766.aspx).

But if you have a fixed number of levels in your hierarchy a self join is a way to go:

SELECT
Emplid = emp.EmplID,
EmployeeName = empname.Name_display,
emp.Supervisor_ID,
SupervisorName = supname.Name_display,
ManagerID = man.EmplID,
ManagerName = manname.Name_display
FROM job AS emp
INNER JOIN name AS empname
ON emp.EmplID = empname.EmplID
LEFT OUTER JOIN name AS supname
ON emp.Supervisor_ID = supname.EmplID
LEFT OUTER JOIN job AS man
ON emp.Supervisor_ID = man.EmplID
LEFT OUTER JOIN name AS manname
ON man.EmplID = manname.EmplID
I created this on the fly without any testing whatsoever but I think it will get what you need. I'm sure you can add the joins for the ApproverID and ApproverName yourself...

- Lumbago
http://xkcd.com/327/
Go to Top of Page
   

- Advertisement -