I have a table as the following:
| branch_id | parent_branch_id | sales |
|---|---|---|
| 1 | 10 | |
| 2 | 1 | 5 |
| 3 | 8 | |
| 4 | 3 | 3 |
| 5 | 1 | 1 |
| 6 | 6 |
I need to aggregate the table on branches of a father branch
| branch_id | sales |
|---|---|
| 1 | 16 |
| 3 | 11 |
| 6 | 6 |
What I have tried:
I tried first separating the branches which have a parent branch and aggregating them on their parent_branch_id, then joining this aggregated table with the table of the parent only branches on t1.parent_branch_id=t2.branch_id and summing the resulting columns to get total sales.
I feel this, having to join tables, is costly and maybe there is a smarter way to do it with builtin PostgreSQL functions.