Hi, I need help with a problem regarding data saved in a parent-children model table and a report I need to build upon it. I've already tried searching for topics about parent-children issues, but I couldn't find anything useful in my scenario.
What I have
A Microsoft SQL Server 2000 database server.
A categories
table, which has four columns: category_id
, category_name
, father_id
and visible
; the categories have x root categories (where x is variable), and could be y level deep (where y is variable), if a category is a root level one it has father_id
null otherwise it's filled with the id of the father category.
A sales
table, which has z columns, one of which is category_id
, a foreign key to categories.category_id
; a sale must always have a category, and it could be linked anywhere in the aforementioned y level.
What I need
I've been asked a report displaying only the root (first level) categories, and the quantity of sales belongings to each of these, or their children, no matter how deep. I.e. if one of the root categories is food
, which has a children category named fruit
, which has a children category named apple
, I need to count every item belonging to food
or fruit
or apple
.
Couldn't you use the nested set data model?
I know of the nested set model, but I already have the table this way, and migrating it to the nested set model would be a pain (let alone I didn't even fully grasp how nested set works), not counting the changes needed in the application using the database. (If someone thinks this is still the least pain way, please explain why and how the current data could be migrated.)
Couldn't you use CTE (Common Table Expressions)?
No, it's a Microsoft SQL Server 2000, and Common Table Expressions are introduced in the 2005 edition.
Thanks in advance, Andrea.