tags:

views:

113

answers:

2

My data fits a tree form naturally. Therefore, I have a simple SQL table to store the data: {id, parentid, data1, ..., dataN}

I want to be able to "zoom in" on the data and produce a report which summarizes the data found below the current branch. That is, when standing in the root, I want to have the totals of all the data. When I have traveled down a certain branch of the tree, I want to only have the summation of the data found only for that node and its child nodes.

How do I write such a query in SQL?

Thanks in advance!

/John

+2  A: 

Since sqlite does not support CONNECT BY, you will not be able to perform this calculation in a single query unless you use nested sets or materialized paths for your data.

Alternatively, do it "the hard way" and traverse your tree recursively, one query for each child node starting at the parent-of-interest.

Also see:

vladr
I was thinking about traversing the children recursively but was hoping for an out-of-the-box solution by SQL.After having read about Materialized paths I immediately felt that that would be a perfect fit for my problem! It will be trivial to implement :-) Thanks! /John
John Lane
+1  A: 

Vlad's reference on nested sets looks pretty good. If you want something that covers trees and hierarchies in more detail then you can also check out Joe Celko's book.

The "ID, ParentID" adjacency list model is really an "old time" way of looking at hierarchies in a relational database model.

Tom H.