これは、@a_horseの正しいの簡略版です。 答え
(コメントでOPと話し合った後)
anyで動作します (合理的に有限の)再帰のレベル数。
指定された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;
すべてのプロジェクトの合計価格
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 こちら
(正しいテストケースを使用)
古い