SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How join two tables? Hierarchical table
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Radzhab
Starting Member

1 Posts

Posted - 11/30/2013 :  03:55:08  Show Profile  Reply with Quote
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

India
52317 Posts

Posted - 11/30/2013 :  04:55:24  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000