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

Rekursiv forespørgsel med sum i Postgres

Dette er en forenklet version af @a_horse's korrekte svar (efter diskussion med OP i kommentarer).
Arbejder med alle (rimeligt begrænset) antal niveauer i rekursionen.

Samlet pris for givet project_id

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;
 

Samlet pris for alle projekter

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<>fiddle her (med korrekt testcase)
Gamle sqlfiddle



  1. MySQL pivottabelforespørgsel med dynamiske kolonner

  2. MySQL 5.7 returnerer alle kolonner i tabellen baseret på en særskilt kolonne

  3. Replikering mellem SQL Server og MYSQL

  4. Muligt at angive unikt indeks med NULL tilladt i Rails/ActiveRecord?