474,048 Members | 1,816 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to express a recursive CTE that returns a balanced hierarchy

for the conext of this example imagine a simple part table where a
part can only have a single parent. try to express a cte where the
result set must be balanced. That is, the result set repeats node B
and E sufficient times that the tree is as deep as node G.

insert into Part ( PartId, PartName, ParentPart) values
( 1,'A',null), (2,'B',1), (3,'C',1), (4,'D',1), (5,'E',3), (6,'F',4),
(7,'G',6)

The following query will not parse as DB2 is complaining about types -
don't seem to be able to avoid that. If I hack the sub-query to fake
things I'm not getting the desired result. Should it be possible vs I
am presuming that one of the recursive CTEs is materialized as I'm
assuming when it should not be (ie. sql standard says my assumption is
wrong).

If this is not viable, does anyone have an example which perhaps
leverages pushing the result set into an XML frag and uses Xquery to
do the inflation I need. Note also, having to express the fake full
path is a cheezy thing as I have to define a max size, force padded
numbers etc to safely do a posstr hence the XML route might be cleaner
in general.

with
parts ( lvl, partkey, parentkey, partname, fullpath ) as
( select 0, partid, parentpart, partname, cast ( digits(p.partid ) as
varchar(2000))
from part p where p.partname='A'
union all
select lvl + 1,c.partid, c.parentpart, c.partname, p.fullpath || '/'
|| digits(c.partid )
from part c, parts p where p.partkey=c.par entpart
),
leaf (partkey, fullpath) as
(
select partkey, fullpath
from parts
where lvl = ( select max (lvl) from parts )
),
balancedtree ( lvl, partkey, parentkey, partname, maxlvl ) as
(
select lvl, partkey, parentkey, partname, ( select max( lvl ) from
parts ) maxlvl
from parts
union all
select lvl + 1, partkey, parentkey, partname, maxlvl
from balancedtree b
where lvl < maxlvl and not exists (
select * from leaf l
where 0 < posstr ( l.fullpath, digits (b.partkey)
)
)
)
select lvl, partkey, partname from balancedtree

Oct 14 '07 #1
4 3608
On Oct 14, 8:54 pm, the6campbells <the6campbe...@ gmail.comwrote:
for the conext of this example imagine a simple part table where a
part can only have a single parent. try to express a cte where the
result set must be balanced. That is, the result set repeats node B
and E sufficient times that the tree is as deep as node G.

insert into Part ( PartId, PartName, ParentPart) values
( 1,'A',null), (2,'B',1), (3,'C',1), (4,'D',1), (5,'E',3), (6,'F',4),
(7,'G',6)

The following query will not parse as DB2 is complaining about types -
don't seem to be able to avoid that. If I hack the sub-query to fake
things I'm not getting the desired result. Should it be possible vs I
am presuming that one of the recursive CTEs is materialized as I'm
assuming when it should not be (ie. sql standard says my assumption is
wrong).

If this is not viable, does anyone have an example which perhaps
leverages pushing the result set into an XML frag and uses Xquery to
do the inflation I need. Note also, having to express the fake full
path is a cheezy thing as I have to define a max size, force padded
numbers etc to safely do a posstr hence the XML route might be cleaner
in general.

with
parts ( lvl, partkey, parentkey, partname, fullpath ) as
( select 0, partid, parentpart, partname, cast ( digits(p.partid ) as
varchar(2000))
from part p where p.partname='A'
union all
select lvl + 1,c.partid, c.parentpart, c.partname, p.fullpath || '/'
|| digits(c.partid )
from part c, parts p where p.partkey=c.par entpart
),
leaf (partkey, fullpath) as
(
select partkey, fullpath
from parts
where lvl = ( select max (lvl) from parts )
),
balancedtree ( lvl, partkey, parentkey, partname, maxlvl ) as
(
select lvl, partkey, parentkey, partname, ( select max( lvl ) from
parts ) maxlvl
from parts
union all
select lvl + 1, partkey, parentkey, partname, maxlvl
from balancedtree b
where lvl < maxlvl and not exists (
select * from leaf l
where 0 < posstr ( l.fullpath, digits (b.partkey)
)
)
)
select lvl, partkey, partname from balancedtree

Didnt have time to investigate what it is your trying to do, but does
it help to replace:

where 0 < posstr ( l.fullpath, digits (b.partkey)

with:

where locate ( digits(b.partke y), l.fullpath ) 0?
/Lennart

Oct 15 '07 #2
On Oct 15, 12:34 am, Lennart <Erik.Lennart.J ons...@gmail.co mwrote:
On Oct 14, 8:54 pm, the6campbells <the6campbe...@ gmail.comwrote:


for the conext of this example imagine a simple part table where a
part can only have a single parent. try to express a cte where the
result set must be balanced. That is, the result set repeats node B
and E sufficient times that the tree is as deep as node G.
insert into Part ( PartId, PartName, ParentPart) values
( 1,'A',null), (2,'B',1), (3,'C',1), (4,'D',1), (5,'E',3), (6,'F',4),
(7,'G',6)
The following query will not parse as DB2 is complaining about types -
don't seem to be able to avoid that. If I hack the sub-query to fake
things I'm not getting the desired result. Should it be possible vs I
am presuming that one of the recursive CTEs is materialized as I'm
assuming when it should not be (ie. sql standard says my assumption is
wrong).
If this is not viable, does anyone have an example which perhaps
leverages pushing the result set into an XML frag and uses Xquery to
do the inflation I need. Note also, having to express the fake full
path is a cheezy thing as I have to define a max size, force padded
numbers etc to safely do a posstr hence the XML route might be cleaner
in general.
with
parts ( lvl, partkey, parentkey, partname, fullpath ) as
( select 0, partid, parentpart, partname, cast ( digits(p.partid ) as
varchar(2000))
from part p where p.partname='A'
union all
select lvl + 1,c.partid, c.parentpart, c.partname, p.fullpath || '/'
|| digits(c.partid )
from part c, parts p where p.partkey=c.par entpart
),
leaf (partkey, fullpath) as
(
select partkey, fullpath
from parts
where lvl = ( select max (lvl) from parts )
),
balancedtree ( lvl, partkey, parentkey, partname, maxlvl ) as
(
select lvl, partkey, parentkey, partname, ( select max( lvl ) from
parts ) maxlvl
from parts
union all
select lvl + 1, partkey, parentkey, partname, maxlvl
from balancedtree b
where lvl < maxlvl and not exists (
select * from leaf l
where 0 < posstr ( l.fullpath, digits (b.partkey)
)
)
)
select lvl, partkey, partname from balancedtree

Didnt have time to investigate what it is your trying to do, but does
it help to replace:

where 0 < posstr ( l.fullpath, digits (b.partkey)

with:

where locate ( digits(b.partke y), l.fullpath ) 0?

/Lennart- Hide quoted text -

- Show quoted text -
no it does not. nor do explicit casts. only literals bypass the
parsing error.

Oct 15 '07 #3
get a copy of TREES & HIERARCHIES ON SQ and look up the nested sets
model instead.

Oct 15 '07 #4
On Oct 16, 7:17 am, Lennart <Erik.Lennart.J ons...@gmail.co mwrote:
[...]
Adjustments and remaining tree

with tc (node, ancestor) as (
select PartId,ParentPa rt from Part
union all
select PartId, ancestor from tc t, Part p
where t.node = p.ParentPart
), leafs(node) as (
select PartId from Part x
where not exists (
select 1 from Part y
where x.Partid = y.ParentPart
)
), leaf_height(nod e, height) as (
select tc.node, count(tc.ancest or) as height
from leafs l, tc
where tc.node = l.node
group by tc.node
), balanced_height (node,parent,he ight) as (
select node,node,heigh t
from leaf_height
where height < (select max(height) from leaf_height)
union all
select node, node, height+1
from balanced_height
where height+1 < (select max(height) from leaf_height)
)
select n.partname, m.partname, x.height
from balanced_height x, part m, part n
where x.node = m.partid
and x.parent = n.partid
union all
select n.partname, m.partname,
(select count(ancestor) from tc where node = n.partid)
from part m, part n
where m.parentpart = n.partid;

/L

Oct 17 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
2526
by: Rolf Kemper | last post by:
Dear All, somehow I remember that such or similar question was discussed already somewhere. But I can't find it anymore. I have a template calling itself. As long it goes deeper into the hierarchy (by the key) I can set the CurrentY parameter by itself + some constant correctly. Hence which each call the CurrentY gets bigger. But when the template reaches a leave and the caller is poped from
2
2904
by: | last post by:
OK: Purpose: Using user's input and 3 recursive functions, construct an hour glass figure. Main can only have user input, loops and function calls. Recursive function 1 takes input and displays a sequence of spaces; recursive function 2 uses input to display ascending sequence of digits; likewise, recursive function 3 uses input to display descending sequence of digits. I have not followed the instructions completely regarding the...
13
409
by: Timothy Madden | last post by:
Hello all I'm facing a very strange problem. I need to define a function that takes as argument something like a pointer to itself. It takes as argument a pointer of the same type as a pointer to itself and with possibly other pointer-to-function value. But I don't have a data type for such a pointer because the function prototype is in the same time being defined. I hope you are following me ... Actualy I need to define a pointer to...
7
2685
by: aurora | last post by:
I love generator and I use it a lot. Lately I've been writing some recursive generator to traverse tree structures. After taking closer look I have some concern on its performance. Let's take the inorder traversal from http://www.python.org/peps/pep-0255.html as an example. def inorder(t): if t: for x in inorder(t.left):
20
18946
by: Gary Manigian | last post by:
I have 2 tables, one-to-many, that contain bills of material(BOMs): tblBOM: lngBOMID (PK) strAssemblyPartNo strDescription tblBOMDetail: lngBOMDetailID (PK) lngBOMID (FK)
7
2250
by: abhrajit | last post by:
I'm looking for a C/C++/Java library to create a balanced binary tree data structure given a set of leaf nodes as input. A leaf node should never become an interior node. So if I wish to create a tree that will have a,b,c & d as leaf nodes - this tree will contain nodes other than a,b,c & d as interior nodes: e.g. x / \
8
3685
by: Andy | last post by:
Hi all, i am pretty new to programming and have a (simple?) problem here: I want to populate a Treeview with data from a table. Table layout is: ID, ParentID, Description There can be infinite levels, the starting level for ParentID is 0 (this is root level). I know that I will have to make a recursive function to fill this
2
2417
by: sebastien.abeille | last post by:
Hello, I would like to create a minimalist file browser using pyGTK. Having read lot of tutorials, it seems to me that that in my case, the best solution is to have a gtk.TreeStore containing all the files and folders so that it would map the file system hierarchy.
3
2399
by: fabiomoggi | last post by:
Hello Guys, I am developing a web application to manage Active Directory resources, and one of my tasks is to map Organizational Units hierarchy into a SQL Server database. Let's suppose that I have the following OU hierarchy in my Active Direcoty: 1. NewYork 1.1 HR_Department 1.1.1 Computers 1.1.2 Users 1.2 SALES_Department 1.1.1 Computers
0
10356
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11616
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
12046
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
11146
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7882
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6667
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6864
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4951
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3983
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.