Редактировал(а) Alexandr Fokin 2023/12/16 14:12

Последние авторы
1 {{code language="sql"}}
2 WITH RECURSIVE r AS (
3
4 -- Нижний уровень дерева (наиболее отдаленный от корня)
5 SELECT distinct
6 1 AS i,
7 s.id,
8 s.name,
9 s.parent,
10 --Локальная сумма (на текущем уровне)
11 sum(COALESCE (t.sum, 0))
12 over (PARTITION by s.id)
13 as localSum,
14 -- Глобальная сумма (агрегирует локальную сумму и сумму подуровне)
15 sum(COALESCE (t.sum, 0))
16 over (PARTITION by s.id)
17 as globalSum
18 from storage s
19 left join transaction t
20 on s.id = t.storage
21 where
22 s.id not in
23 (
24 select s2.parent
25 from storage s2
26 where s2.parent is not null
27 )
28 UNION
29
30 -- Последующий уровень вверх
31 SELECT distinct
32 i+1 AS i,
33 s.id,
34 s.name,
35 s.parent,
36 --Локальная сумма (на текущем уровне)
37 sum(COALESCE (t.sum, 0))
38 over (PARTITION by s.id)
39 as localSum,
40 -- Глобальная сумма (агрегирует локальную сумму и сумму подуровне)
41 sum(COALESCE (t.sum, 0) + r.globalSum)
42 over (PARTITION by s.id)
43 as globalSum
44 FROM storage s
45 join r
46 on r.parent = s.id
47 left join transaction t
48 on s.id = t.storage
49 )
50
51
52 SELECT
53 r.*
54 FROM r
55 order by r.id
56 {{/code}}
57
58 ----
59
60
61 Aggregate functions are not allowed in a recursive query. Is there an alternative way to write this query?
62 https://stackoverflow.com/questions/57299663/aggregate-functions-are-not-allowed-in-a-recursive-query-is-there-an-alternativ