2 つの階層的な CONNECT BY クエリで UNION ALL を使用する Oracle のソリューションを見つけました。1 つは祖先をフェッチし、もう 1 つは子をフェッチします。DB2とSQL Server
の両方で同じことを達成したいと考えています。
1 つの要素が階層のルート、ブランチ、またはリーフである可能性があることを知っています。その階層全体を取得する必要があります。
itemid ='item3' と class='my class'があり、その祖先と子を見つける必要があるとします。
with ancestor (class, itemid, parent, base, depth)
as (
select root.class, root.itemid, root.parent, root.itemid, 0
from item root
where root.class = 'myclass'
and root.itemid = 'item3'
-- union all
-- select child.class, child.itemid, child.parent, root.base, root.depth+1
-- from ancestor root, item child
-- where child.class = root.class
-- and child.parent = root.itemid
union all
select parent.class, parent.itemid, parent.parent, parent.itemid, root.depth-1
from ancestor root, item parent
where parent.class = root.class
and parent.itemid = root.parent
)
select distinct class, itemid, parent, base, depth
from ancestor
order by class, base, depth asc, itemid
私はこのような結果が欲しい:
class itemid parent base depth
myclass item1 null item3 -2
myclass item2 item1 item3 -1
myclass item3 item2 item3 0
myclass item4 item3 item3 1
myclass item5 item5 item3 2
上記の SQL が実行されると、祖先が正常に取得されます。コメントを削除すると、無限ループになっているようです。それを機能させる方法があるはずです。
階層の一方向 (祖先または子) で結果を取得できますが、1 つのクエリで両方を取得することはできません。
誰かがそのようなことを試したことがありますか?
ありがとう