gpt4 book ai didi

SQL Server 递归查询以显示父路径

转载 作者:行者123 更新时间:2023-12-05 09:08:26 26 4
gpt4 key购买 nike

我正在使用 SQL Server 语句并有一个表,如:

| item | value | parentItem |
+------+-------+------------+
| 1 | 2test | 2 |
| 2 | 3test | 3 |
| 3 | 4test | 4 |
| 5 | 1test | 1 |
| 6 | 3test | 3 |
| 7 | 2test | 2 |

我想使用 SQL Server 语句获得以下结果:

| item1 | value1                   |
+-------+--------------------------+
| 1 | /4test/3test/2test |
| 2 | /4test/3test |
| 3 | /4test |
| 5 | /4test/3test/2test/1test |
| 6 | /4test/3test |
| 7 | /4test/3test/2test |

我没有找出正确的 SQL 来根据 parentItem 获取所有 id 的所有值。

我试过这个SQL:

with all_path as 
(
select item, value, parentItem
from table

union all

select a.item, a.value, a.parentItem
from table a, all_path b
where a.item = b.parentItem
)
select
item as item1,
stuff(select '/' + value
from all_path
order by item asc
for xml path ('')), 1, 0, '') as value1
from
all_path

但是在结果中得到了“value1”列

/4test/4test/4test/3test/3test/3test/3test/2test/2test/2test/2test

你能帮我解决这个问题吗?非常感谢。

最佳答案

根据你给出的预期输出,使用递归部分拼接值

;with yourTable as (
select item, value, parentItem
from (values
(1,'2test',2)
,(2,'3test',3)
,(3,'4test',4)
,(5,'1test',1)
,(6,'3test',3)
,(7,'2test',2)
)x (item,value,parentItem)
)
, DoRecursivePart as (

select 1 as Pos, item, convert(varchar(max),value) value, parentItem
from yourTable
union all
select drp.pos +1, drp.item, convert(varchar(max), yt.value + '/' + drp.value), yt.parentItem
from yourTable yt
inner join DoRecursivePart drp on drp.parentItem = yt.item

)
select drp.item, '/' + drp.value
from DoRecursivePart drp
inner join (select item, max(pos) mpos
from DoRecursivePart
group by item) [filter] on [filter].item = drp.item and [filter].mpos = drp.Pos
order by item

给予

item        value
----------- ------------------
1 /4test/3test/2test
2 /4test/3test
3 /4test
5 /4test/3test/2test/1test
6 /4test/3test
7 /4test/3test/2test

关于SQL Server 递归查询以显示父路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63489281/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com