PostgreSQL
 sql >> Database >  >> RDS >> PostgreSQL

Query ricorsiva con somma in Postgres

Questa è una versione semplificata di @a_horse's correct rispondi (dopo la discussione con OP nei commenti).
Funziona con qualsiasi (ragionevolmente finito) numero di livelli nella ricorsione.

Prezzo totale per project_id specificato

WITH RECURSIVE cte AS (
   SELECT project_id AS project_parent, project_value
   FROM   projects
   WHERE  project_id = 1 -- enter id of the base project here !

   UNION  ALL 
   SELECT p.project_id, p.project_value
   FROM   cte
   JOIN   projects p USING (project_parent)
)
SELECT sum(project_value) AS total_value
FROM   cte;

Prezzo totale per tutti i progetti

WITH RECURSIVE cte AS (
   SELECT project_id, project_id AS project_parent, project_value
   FROM   projects
   WHERE  project_parent IS NULL  -- all base projects

   UNION  ALL 
   SELECT c.project_id, p.project_id, p.project_value
   FROM   cte c
   JOIN   projects p USING (project_parent)
   )
SELECT project_id, sum(project_value) AS total_value
FROM   cte
GROUP  BY 1
ORDER  BY 1;

db<>violino qui (con test case corretto)
Vecchio sqlfiddle