sql >> Databasteknik >  >> RDS >> PostgreSQL

Rekursiv fråga med summa i Postgres

Detta är en förenklad version av @a_horse's korrekta svara (efter diskussion med OP i kommentarer).
Fungerar med alla (rimligt ändligt) antal nivåer i rekursionen.

Totalt pris för given 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;

Totalpris för alla projekt

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<>fiol här (med korrekt testfall)
Gammal sqlfiddle



  1. Postgres generera_serie

  2. Hantering av latens i MySQL-transaktioner

  3. LADDA DATAINFIL med variabler

  4. Interner i de sju SQL-serversorterna – Del 1