I am working with the following table
-- USER TABLE --
User_ID | Manager_ID | Code
1 | null | ABC
2 | 1 | DEF
3 | 2 | HIJ
4 | null | ABC
I need to know the codes related to each user, and if the code is “owned” or not. The associated code "belongs" to the user when the code is on the same line
User_ID = 1 : Native code = ABC
But I also need to know the codes associated for each user in the Manager_ID → User_ID hierarchy. This hierarchy has no maximum depth.
User_ID = 1 : Associated code = DEF (by User_ID 2) and HIJ (by User_ID 3)
In my example, I would like to get the following result
User_ID | Code | IsOwner
1 | ABC | 1
1 | DEF | 0
1 | HIJ | 0
2 | DEF | 1
2 | HIJ | 0
3 | HIJ | 1
4 | ABC | 1
For the existing code, I simply executed the following query:
SELECT User_ID, Code, 1 as IsOwner
FROM User
. , "" "", , .
Common Table Expression , , - ...
USE MyBD
GO
WITH MyCTE (Manager_ID, User_ID, Code, IsOwned)
AS
(
SELECT Manager_ID, User_ID, Code, 1 as IsOwned
FROM User
WHERE Manager_ID IS NULL
UNION ALL
SELECT u.Manager_ID, u.User_ID, u.Code, 1 as IsOwned
FROM User AS u
INNER JOIN Managers AS d
ON u.Manager_ID = d.User_ID
)
SELECT Manager_ID, User_ID, Code, IsOwned
FROM Managers
GO
?