I have a data table that contains data that is technically a tree structure, but the tree is determined by the code and the length of this code.
The table Product code consists of a code and description:
For instance:
Code Description
------ -------------
0101 Live Animals
01011 Horses
010110 Purebred
010190 Other
The element level is calculated by counting the codes below it. The code below it should be contained in the current code. If that makes sense.
So in the example above:
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)
Is there a way to get these levels in SQL? I am using DB2.
EDIT:
Both Nikola and Gordon solutions work well, although I think Nikola is a little faster! Thanks guys!
You will have to make a few changes to account for 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
source
share