我正在尝试构建一个 t-sql 查询,该查询将根据汇总输入在同一个表中返回父帐户及其子帐户。有人可以帮忙吗?
***TABLE:USERS***
UserId ParentId
66 -1
67 -1
68 -1
69 54
70 55
71 56
72 57
这是我到目前为止所拥有的,但它只返回一个帐户,这是最后一个帐户,我需要在递归中包含 ParentId,这样它就会一个接一个地拉出父帐户和子帐户的列表。
DECLARE @RollUp AS bit
DECLARE @ParentID As INT
SELECT @RollUp = 0
If @Rollup = 1 SELECT @ParentID = CASE WHEN ParentID = -1
THEN Users.USER_ID
Else ParentID END
FROM Users WHERE user_Id IN (70,71) ELSE
SELECT @ParentID = Users.USER_ID
FROM Users WHERE USER_Id IN (70,71) ;
WITH TRAVERSE_TREE_CTE AS
(
Select User_ID,ParentID
FROM Users
WHERE User_ID = @ParentID
UNION ALL Select Users.User_ID, Users.ParentID
FROM TRAVERSE_TREE_CTE INNER
JOIN Users
ON TRAVERSE_TREE_CTE.User_ID = Users.ParentID
)
Select * from Users
where User_id IN (SELECT distinct User_ID FROM TRAVERSE_TREE_CTE)