I am new to CTE in SQL Server. I am trying with the example from https://www.mssqltips.com/sqlservertip/1520/recursive-queries-using-common-table-expressions-cte-in-sql-server/
I wan to get only the employees reporting to a manager who are having a record in another table i.e UserTag
table eg: In the following table, UserId: 100 is what my test user, he has got following manager hierarchy. Someone in his manager hierarchy, got a record in UserTag. i want that manager id.
This should happen for all users in 'User' table.
User
====
UserId ManagerId
100 101
101 102
102 103
103 104
UserTag
========
Id UserId TagId TagName
1 103 1 'test'
Expected Result:
UserId ManagerWithTagId
100 103
WITH Managers AS
(
-- initialization
SELECT Id, Email, ManagerID
FROM dbo.[User]
UNION ALL
-- recursive execution
SELECT u.Id, u.Email, u.ManagerID
FROM dbo.[User] u
INNER JOIN Managers m ON m.ManagerID = u.ID
--INNER JOIN UserTag UT ON UT.UserId = u.ID
WHERE UT.TagName = 'test'
)
SELECT *
FROM Managers
With the above query i.e commented the UserTag table. i am getting the complete manager hierarchy of particular user. But not sure how to proceed to get my expected result?
Can anyone help me how to achieve this?