This is a simplified version of a problem I am encountering in PostgreSQL.
I have the following table A:
[ ID INTEGER | VALUE NUMERIC(10,2) | PARENT INTEGER ]
Where 'PARENT' is a self-referencing FK to column ID.
The table definition is:
CREATE TABLE A(ID INTEGER IDENTITY, VALUE NUMERIC(10,2), PARENT INTEGER)
ALTER TABLE A ADD CONSTRAINT FK FOREIGN KEY (PARENT) REFERENCES A(ID)
This simple table allows one to define tree data structures of arbitrary depth. Now I need to write a SQL (I prefer not to use server-side PL-SQL) that reports for each node, the total value of the sub-tree "hanging" under it. For instance, with the following table:
| ID | VALUE | PARENT |
-------------------------
| 1 | NULL | NULL |
| 2 | 3.50 | 1 |
| 3 | NULL | NULL |
| 4 | NULL | 3 |
| 5 | 1.50 | 4 |
| 6 | 2.20 | 4 |
I should get the following result set:
| ID | Total-Value-of-Subtree |
| 1 | 3.50 |
| 2 | 3.50 |
| 3 | 3.70 |
| 4 | 3.70 |
| 5 | 1.50 |
| 6 | 2.20 |
For simplicitly, you can assume that only leaf nodes have values, non-leaf nodes always have a value of NULL in the VALUE column. Is there a way to do this in SQL, even utilizing PostgreSQL-specific extensions?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…