Thursday, January 5, 2017

SQL Server -Recurrsive Common Table Expression

---recurrsive common table expression
CREATE TABLE ProjectMemberDetails
(
ID int Identity(1,1) PRIMARY KEY,
TeamMemNm varchar(100),
Designation varchar(50),
ManagerID int NULL
)

-- Insert some sample records in the ProjectMemberDetails table
INSERT INTO ProjectMemberDetails VALUES('Tim','Engagement Manager',NULL);
INSERT INTO ProjectMemberDetails VALUES('Kathy','Sr. Project Manager',1);
INSERT INTO ProjectMemberDetails VALUES('Levonca','Project Manager',2);
INSERT INTO ProjectMemberDetails VALUES('Sid','Project Manager',2);
INSERT INTO ProjectMemberDetails VALUES('Carrie','Project Leader',3);
INSERT INTO ProjectMemberDetails VALUES('Cristina','Project Leader',4);
INSERT INTO ProjectMemberDetails VALUES('Santi','Team Leader',5);
INSERT INTO ProjectMemberDetails VALUES('Michelle','Team Leader',5);
INSERT INTO ProjectMemberDetails VALUES('Pablo','Team Leader',6);
INSERT INTO ProjectMemberDetails VALUES('Mario','Team Leader',6);
INSERT INTO ProjectMemberDetails VALUES('Anand','Sr. Developer',7);
INSERT INTO ProjectMemberDetails VALUES('Bill','Sr. Developer',7);
INSERT INTO ProjectMemberDetails VALUES('Jack','Sr. Developer',8);
INSERT INTO ProjectMemberDetails VALUES('Tibre','Sr. Developer',8);
INSERT INTO ProjectMemberDetails VALUES('Lisa','Sr. Developer',9);
INSERT INTO ProjectMemberDetails VALUES('Scott','Sr. Tester',10);
INSERT INTO ProjectMemberDetails VALUES('Nancy','Developer',11);
INSERT INTO ProjectMemberDetails VALUES('MJ','Developer',12);
INSERT INTO ProjectMemberDetails VALUES('Ziak','Developer',13);
INSERT INTO ProjectMemberDetails VALUES('Martin','Developer',14);
INSERT INTO ProjectMemberDetails VALUES('David','Developer',14);
INSERT INTO ProjectMemberDetails VALUES('Steve','Developer',15);
INSERT INTO ProjectMemberDetails VALUES('Rachael','Developer',15);
INSERT INTO ProjectMemberDetails VALUES('Sally','Tester',16);
INSERT INTO ProjectMemberDetails VALUES('Peter','Tester',16);
SELECT * FROM ProjectMemberDetails;
 go
 WITH CTE(ID, TeamMemberName, Designation, ManagerID, ProjectLevel)
AS
(
SELECT ID, TeamMemNm, Designation, ManagerID, 1 as ProjectLevel
From ProjectMemberDetails WHERE ManagerID is NULL
UNION ALL
SELECT e.ID, e.TeamMemNm, e.Designation, e.ManagerID, c.ProjectLevel + 1
FROM ProjectMemberDetails e
INNER JOIN CTE c
ON e.ManagerID = c.ID
)
SELECT ID, TeamMemberName, Designation, ManagerID, ProjectLevel
FROM CTE Order BY ID

No comments:

Search This Blog

DAX - Grouping on multiple columns and the count

Please go thorugh the below URL for entire soultion. http://community.powerbi.com/t5/Desktop/DAX-Grouping-on-multiple-columns-and-the-cou...