Dans DB2 SQL, j'ai une table qui contient 3 colonnes: parent_id
, id
et count
. C'est une table de hiérarchie. J'ai besoin d'une requête récursive pour obtenir tous les noeuds feuilles et leur nombre total, et une autre requête pour obtenir tous les noeuds feuilles et leur nombre total plus le coût de chaque noeud (le prix est stocké dans une autre table (id
, price
))Comment obtenir les nœuds feuilles par requête récursive dans db2?
J'ai essayé cette requête, mais cela n'a pas fonctionné:
with COMP_P (COMPONENT,SUBCOMPONENT,SUBCOMPCOUNT) as (
(select C.COMPONENT,C.SUBCOMPONENT,C.SUBCOMPCOUNT from COMPS C WHERE C.COMPONENT = 'A')
UNION ALL
(SELECT P.COMPONENT,C.SUBCOMPONENT,C.SUBCOMPCOUNT * P.SUBCOMPCOUNT from COMPS C,COMP_P P WHERE P.SUBCOMPONENT = C.COMPONENT))
SELECT COMPONENT,SUBCOMPONENT,sum(SUBCOMPCOUNT) As Count FROM COMP_P group by COMPONENT,SUBCOMPONENT ;
il me donne des noeuds de feuilles et autres. J'ai essayé pour la deuxième partie:
with COMP_P (COMPONENT,SUBCOMPONENT,SUBCOMPCOUNT) as (
(select C.COMPONENT,C.SUBCOMPONENT,C.SUBCOMPCOUNT from COMPS C WHERE C.COMPONENT = 'A')
UNION ALL
(SELECT P.COMPONENT,C.SUBCOMPONENT,C.SUBCOMPCOUNT * P.SUBCOMPCOUNT from COMPS C,COMP_P P WHERE P.SUBCOMPONENT = C.COMPONENT))
SELECT COMPONENT,SUBCOMPONENT,sum(SUBCOMPCOUNT) As Count,sum(SUBCOMPCOUNT) * partcosts.cost FROM COMP_P,partcosts where partcosts.partid.id=COMP_P.SUBCOMPONENT group by COMPONENT,SUBCOMPONENT ;