postgresql 每个节点级别的Postgres分层聚合

1cosmwyk  于 2023-11-18  发布在  PostgreSQL
关注(0)|答案(1)|浏览(134)

我在postgres中有以下表结构
| ID|父ID|平衡|
| --|--|--|
| 1 |null| 1000 |
| 2 | 1 | 1000 |
| 3 | 1 | 1000 |
| 4 | 2 | 1000 |
| 5 | 2 | 1000 |
| 6 | 3 | 1000 |
| 7 | 3 | 1000 |
| 8 | 4 | 1000 |
我想写一个查询,它给我以下输出(聚合在每个节点级别)
| ID|父ID|平衡|总平衡|
| --|--|--|--|
| 1 |null| 1000 | 8000 |
| 2 | 1 | 1000 | 4000 |
| 3 | 1 | 1000 | 3000 |
| 4 | 2 | 1000 | 2000 |
| 5 | 2 | 1000 | 1000 |
| 6 | 3 | 1000 | 1000 |
| 7 | 3 | 1000 | 1000 |
| 8 | 4 | 1000 | 1000 |
我已经试过查询,但这不是我预期的输出
| D|父ID|平衡|总平衡|
| --|--|--|--|
| 1 || 1000 | 1000 |
| 2 | 1 | 1000 | 2000 |
| 3 | 1 | 1000 | 2000 |
| 4 | 2 | 1000 | 3000 |
| 5 | 2 | 1000 | 3000 |
| 6 | 3 | 1000 | 3000 |
| 7 | 3 | 1000 | 3000 |
| 8 | 4 | 1000 | 4000 |
例如:- id 1的聚合值应为8000(id 2聚合(4000)+ id 3聚合(3000)+ id 1(1000))

8e2ybdfx

8e2ybdfx1#

必须使用递归CTE。
试试这个:

WITH RECURSIVE sum_recursive AS (
    SELECT id, balance, id as parent_id
    FROM your_table 

    UNION ALL

    SELECT t.id, t.balance, sr.parent_id
    FROM your_table AS t
    JOIN sum_recursive sr ON sr.id = t.parent_id
)
SELECT parent_id, SUM(balance) as total_balance
FROM sum_recursive
GROUP BY parent_id;

字符串
小提琴:https://www.db-fiddle.com/f/cRk7bKEZX5vYqTSauqWXWa/0

相关问题