Subject | "Roll up" SQL Statement |
---|---|
Author | red_october_canada |
Post date | 2006-09-18T23:21:52Z |
I have a Firebird 1.5.3 database with a table in it with the structure:
PAR_RID NUMERIC(18,0),
KEY_RID NUMERIC(18,0),
LEVEL INTEGER DEFAULT 0,
QTY INTEGER DEFAULT 0
PAR_RID = Parent Record ID
KEY_RID = Key Record ID
LEVEL = Level in a tree
QTY = Quantity
The table is the basis for a "tree" structure.
The LEVEL field is present just on a hunch that I might need it.
My question is this... I have to SUM() all the QTY fields the root
node, and all of it's children and all children of all their children,
and their children, and their children, etc. etc. so that each 'node'
can display only the sum of all it's own descendants and the only node
that shows a total of every other node including itself, is the root node.
Is there a 'standard'/'well known' way (SQL statment) for doing this?
I will add more fields if necessary. I will take any approach, one
that requires storing totals based on BEFORE/AFTER UPDATE,
BEFORE/AFTER INSERT triggers, or an approach that calculates 'live'
based on user clicking a button.
Thanks in advance for any help.
PAR_RID NUMERIC(18,0),
KEY_RID NUMERIC(18,0),
LEVEL INTEGER DEFAULT 0,
QTY INTEGER DEFAULT 0
PAR_RID = Parent Record ID
KEY_RID = Key Record ID
LEVEL = Level in a tree
QTY = Quantity
The table is the basis for a "tree" structure.
The LEVEL field is present just on a hunch that I might need it.
My question is this... I have to SUM() all the QTY fields the root
node, and all of it's children and all children of all their children,
and their children, and their children, etc. etc. so that each 'node'
can display only the sum of all it's own descendants and the only node
that shows a total of every other node including itself, is the root node.
Is there a 'standard'/'well known' way (SQL statment) for doing this?
I will add more fields if necessary. I will take any approach, one
that requires storing totals based on BEFORE/AFTER UPDATE,
BEFORE/AFTER INSERT triggers, or an approach that calculates 'live'
based on user clicking a button.
Thanks in advance for any help.