gpt4 book ai didi

sql - 根据 SQL 中的代码计算树级别

转载 作者:行者123 更新时间:2023-12-04 15:55:21 25 4
gpt4 key购买 nike

我有一个数据表,其中包含技术上是树结构的数据,但树是由代码和该代码的长度定义的。

商品代码表由代码和描述组成:

例如:

Code    Description
------ -------------
0101 Live Animals
01011 Horses
010110 Purebred
010190 Other

元素的等级是通过计算其下方的代码来计算的。它下面的代码必须包含在当前代码中。如果这有任何意义。

所以在上面的例子中:

0101   is level 0 (nothing is contained in it)
01011 is level 1 (0101 is contained in it)
010110 is level 2 (0101 and 01011 is contained in it)
010190 is level 1 (only 0101 is contained in it)

有没有办法在 SQL 中获得这些级别?我正在使用 DB2。

编辑:Nikola 和 Gordon 的解决方案都运行良好,尽管我认为 Nikola 的解决方案要快一些!谢谢各位!

必须对 DB2 进行一些修改:

select
t1.code, count(t2.code)
from commoditycode t1
left join commoditycode t2
on substr(t1.code, 1, length(t1.code) - 1) like concat(t2.code, '%')
group by t1.code

最佳答案

在减去最后一个字符的代码上加入自身将在右侧找到所有父级。数一数就可以得到元素的等级:

declare @test table (code varchar(10), name varchar(100))

insert into @test values ('0101', 'Live Animals')
insert into @test values ('01011', 'Horses')
insert into @test values ('010110', 'Purebred')
insert into @test values ('010190', 'Other')

select t1.code, t1.name, count (t2.code) + 1 [level]
from @test t1
left join @test t2
on substring (t1.code, 1, len (t1.code) - 1) like t2.code + '%'
group by t1.code, t1.name


code name level
01011 Horses 2
0101 Live Animals 1
010190 Other 2
010110 Purebred 3

关于sql - 根据 SQL 中的代码计算树级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10500729/

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