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
 Hierarchical working...
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

asif372
Posting Yak Master

Pakistan
100 Posts

Posted - 11/04/2013 :  07:08:41  Show Profile  Reply with Quote
i am working on Attendance System i want to work on hierarchy Structure
Boss EmployeeID is Employee ID of First Immediate Boss.

just like Employee ID 5 HAVE 4 BOSS's EmployeeID's of Bosses are 4,3,2,1


My Date is like this
Employee ID Name Boss Employee ID
1 ABC NULL
2 DEF 1
3 GHI 2
4 JKL 3
5 MNO 4

11 ABC NULL
12 1DEF 11
13 1GHI 12
14 1JKL 13
15 1MNO 14

i want to Display Subornates of Every Boss
my required data is like this

Sub Ordinates
Employee ID Name Subornates ID
1 ABC 2,3,4,5
2 DEF 3,4,5
3 GHI 4,5
4 JKL 5
5 MNO NULL

11 ABC 12,13,14
12 1DEF 13,14,15
13 1GHI 14,15
14 1JKL 15
15 1MNO NULL

Thanks in Advance

Edited by - asif372 on 11/04/2013 07:13:18

visakh16
Very Important crosS Applying yaK Herder

India
52309 Posts

Posted - 11/04/2013 :  07:21:44  Show Profile  Reply with Quote


declare @emp table
(
EmployeeID int,
Name varchar(5),
BossEmployeeID int
)
insert @emp
values(1,'ABC', NULL),
(2, 'DEF', 1),
(3, 'GHI', 2),
(4, 'JKL', 3),
(5, 'MNO', 4),

(11, 'ABC' ,NULL),
(12, '1DEF', 11),
(13, '1GHI', 12),
(14, '1JKL', 13),
(15, '1MNO', 14)

;With OrgHierarchy
AS
(
SELECT  t.[EmployeeID],t.Name ,t.BossEmployeeID, CAST(NULL AS varchar(max)) AS [BossesID]
FROM @emp t
WHERE NOT EXISTS (SELECT 1
FROM @emp WHERE  [BossEmployeeID] = t.[EmployeeID])
UNION ALL
SELECT t.[EmployeeID],t.[Name],t.BossEmployeeID,CAST(CAST(oh.[EmployeeID] AS varchar(10)) +COALESCE( ',' + oh.[BossesID],'') AS varchar(max))
FROM OrgHierarchy oh
INNER JOIN @emp t
ON t.[EmployeeID] = oh.[BossEmployeeID]
)

SELECT [EmployeeID],[Name],[BossesID]
FROM OrgHierarchy
ORDER BY [EmployeeID]
OPTION (MAXRECURSION 0)


output
-----------------------------------
EmployeeID	Name	BossesID
-----------------------------------
1	        ABC	2,3,4,5
2	        DEF	3,4,5
3	        GHI	4,5
4	        JKL	5
5	        MNO	NULL
11	        ABC	12,13,14,15
12	       1DEF	13,14,15
13	       1GHI	14,15
14	       1JKL	15
15	       1MNO	NULL



------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs

Edited by - visakh16 on 11/04/2013 07:30:29
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.05 seconds. Powered By: Snitz Forums 2000