Counting number of children in hierarchical SQL data
ALTER PROCEDURE [dbo].[GetEmployeesstaffwise2] ( @id varchar(30) , @unitid varchar(40))
AS ;
WITH EmployeeManager
AS(
SELECT distinct Boss.ID, tbl_Staff.Firstname+' '+tbl_Staff.Middlename+' '+tbl_Staff.Lastname Employee , Boss.Firstname+' '+Boss.Middlename+' '+Boss.Lastname Boss FROM tbl_Staff
INNER JOIN tbl_Staff AS Boss ON tbl_Staff.mgr=Boss.ID
INNER JOIN tbl_Staff BigBoss ON Boss.ID=BigBoss.mgr or tbl_Staff.mgr=Boss.ID
where BigBoss.mgr=@id and Boss.UnitID like'%'+@unitid+'%' and BigBoss.UnitID like'%'+@unitid+'%' and tbl_Staff .UnitID like'%'+@unitid+'%'
) select ID,employee as name,Boss as manager from EmployeeManager
ID ParentID name Children
1 NULL kk 9
2 1 jin 8
3 2 NULL 3
4 2 NULL 2
5 3 NULL 1
6 2 NULL 0
7 3 NULL 0
8 4 NULL 0
9 4 NULL 0
10 5 NULL 0
;WITH ChildrenCTE AS (
SELECT RootID = ID, ID
FROM [treestructure]
UNION ALL
SELECT cte.RootID, d.ID
FROM ChildrenCTE cte
INNER JOIN [treestructure] d ON d.ParentID = cte.ID
)
SELECT d.ID, d.ParentID, d.name, cnt.Children
FROM [treestructure] d
INNER JOIN (
SELECT ID = RootID, Children = COUNT(*) - 1
FROM ChildrenCTE
GROUP BY RootID
) cnt ON cnt.ID = d.ID
AS ;
WITH EmployeeManager
AS(
SELECT distinct Boss.ID, tbl_Staff.Firstname+' '+tbl_Staff.Middlename+' '+tbl_Staff.Lastname Employee , Boss.Firstname+' '+Boss.Middlename+' '+Boss.Lastname Boss FROM tbl_Staff
INNER JOIN tbl_Staff AS Boss ON tbl_Staff.mgr=Boss.ID
INNER JOIN tbl_Staff BigBoss ON Boss.ID=BigBoss.mgr or tbl_Staff.mgr=Boss.ID
where BigBoss.mgr=@id and Boss.UnitID like'%'+@unitid+'%' and BigBoss.UnitID like'%'+@unitid+'%' and tbl_Staff .UnitID like'%'+@unitid+'%'
) select ID,employee as name,Boss as manager from EmployeeManager
ID ParentID name Children
1 NULL kk 9
2 1 jin 8
3 2 NULL 3
4 2 NULL 2
5 3 NULL 1
6 2 NULL 0
7 3 NULL 0
8 4 NULL 0
9 4 NULL 0
10 5 NULL 0
;WITH ChildrenCTE AS (
SELECT RootID = ID, ID
FROM [treestructure]
UNION ALL
SELECT cte.RootID, d.ID
FROM ChildrenCTE cte
INNER JOIN [treestructure] d ON d.ParentID = cte.ID
)
SELECT d.ID, d.ParentID, d.name, cnt.Children
FROM [treestructure] d
INNER JOIN (
SELECT ID = RootID, Children = COUNT(*) - 1
FROM ChildrenCTE
GROUP BY RootID
) cnt ON cnt.ID = d.ID
Comments
Post a Comment