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
 How join two tables? Hierarchical table

Author  Topic 

Radzhab
Starting Member

1 Post

Posted - 2013-11-30 : 03:55:08
have two table. Department is hierarchical table.

Department
--- id (int primary key)
--- name (varchar)
--- parent (int)

Users
--- Id
--- name
--- department_id

This query return all data from departments. But i cannot understand how get data from users

SELECT t1.name AS lvl1, t2.name as lvl2, t3.name as lvl3
FROM Department AS t1
LEFT JOIN Department AS t2 ON t2.parent = t1.id
LEFT JOIN Department AS t3 ON t3.parent = t2.id

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-11-30 : 04:55:24
sounds like this


;With Dept_Hierarchy
AS
(
SELECT s.id as UserID,s.name AS UserName,d.name AS DeptName,d.id AS DeptID,d.parent AS ParentDeptID
FROM Users s
JOIN Department d
ON d.id = s.department_id
UNION ALL
SELECT u.id,u.name,d.name,d.id,d.parent
FROM Dept_Hierarchy dh
JOIN Department d
ON d.id = dh.ParentDeptID
JOIN Users u
ON u.department_id = d.id
)

SELECT *
FROM Dept_Hierarchy
OPTION (MAXRECURSION 0)


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -