I have a data table that contains data which is technically a tree structure, but the tree is defined by a code and the length of this code.
The Commodity Code table consists of a code and a description:
For example:
Code Description
------ -------------
0101 Live Animals
01011 Horses
010110 Purebred
010190 Other
The level of an item is calculated by counting the codes beneath it. The code beneath it must be contained in the current code. If that makes any sense.
So in the above example:
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’s solutions work well, although I think Nikola’s is slightly quicker! Thank you guys!
Had to make a few edits 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
A join to itself on code minus last character will find all parents on the right side. Counting them will get the level of item: