我正在尝试构建一个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)
答案 0 :(得分:0)
你在递归中引用绝对是我认为的问题。
Where User_ID = @ParentID
在递归部分之后,通常不会执行谓词。您有时可能会在递归表达式中使用绝对值通常会产生不可预测的结果,因为您尝试将其显式并仅在一个实例上连接到它的父级。但是,您经常需要告诉表达式您要查找的递归级别以及该级别之后的谓词已确定。
这是一个可以帮助自我填充的例子。它将查找最大递归级别并仅确定该级别。
Declare @table table ( PersonId int identity, PersonName varchar(512), Account int, ParentId int, Orders int);
insert into @Table values ('Brett', 1, NULL, 1000),('John', 1, 1, 100),('James', 1, 1, 200),('Beth', 1, 2, 300),('John2', 2, 4, 400);
select
PersonID
, PersonName
, Account
, ParentID
from @Table
; with recursion as
(
select
t1.PersonID
, t1.PersonName
, t1.Account
--, t1.ParentID
, cast(isnull(t2.PersonName, '')
+ Case when t2.PersonName is not null then '\' + t1.PersonName else t1.PersonName end
as varchar(255)) as fullheirarchy
, 1 as pos
, cast(t1.orders +
isnull(t2.orders,0) -- if the parent has no orders than zero
as int) as Orders
from @Table t1
left join @Table t2 on t1.ParentId = t2.PersonId
union all
select
t.PersonID
, t.PersonName
, t.Account
--, t.ParentID
, cast(r.fullheirarchy + '\' + t.PersonName as varchar(255))
, pos + 1 -- increases
, r.orders + t.orders
from @Table t
join recursion r on t.ParentId = r.PersonId
)
, b as
(
select *, max(pos) over(partition by PersonID) as maxrec -- I find the maximum occurrence of position by person
from recursion
)
select *
from b
where pos = maxrec -- finds the furthest down tree
-- and Account = 2 -- I could find just someone from a different department
<强>已更新强>
如果您只想查看与变量ID相关的子元素,您可以将表连接回自身而不使用递归。
Declare @table table ( PersonId int identity, PersonName varchar(512), Account int, ParentId int, Orders int);
insert into @Table values ('Brett', 1, NULL, 1000),('John', 1, 1, 100),('James', 1, 1, 200),('Beth', 1, 2, 300),('John2', 2, 4, 400);
declare @Id int = 1 -- set to 1, 2, 3, 4, 5
select
a.PersonName
, isnull(b.PersonName,'No Child') as [ChildName(s)]
from @table a
left join @table b on a.Personid = b.ParentId
where a.PersonId = @Id