I have the following tables:
Categories
=================================
CategoryID | ParentID | Text
---------------------------------
1 NULL Text
2 1 Text
3 NULL Text
4 1 Text
Items
=================================
ItemID | CategoryID | Text
---------------------------------
1 1 Text
2 2 Text
3 4 Text
4 3 Text
Bear in mind this is not an n-level hierarchy, the categories have only 2 levels, so no category can have a parentID of 2 for instance.
What I am looking for is a way to return the categories with an extra column which displays the number of items that the category owns (including its subcategories).
i.e. I’m looking for a single query (or procedure) which can return something like the following:
Categories
============================================
CategoryID | ParentID | Text | Count
--------------------------------------------
1 NULL Text 3
2 1 Text 1
3 NULL Text 1
4 1 Text 1
My current method of getting the items associated to a category is as follows (Given a categoryID, @CategoryID):
SELECT * FROM Items
WHERE CategoryID
IN (SELECT CategoryID FROM Categories where ParentID = @CategoryID or CategoryID = @CategoryID)
My problem is that I cannot seem to link this to a select query for the categories themselves.
It’s probably very simple, but I have tried methods using CTE’s, various group by clauses, but the hierarchical nature of the categories seems to throw my logic off.
Thanks for any help!
EDIT: The query also needs to account for categories with no items associated to them
You’d have to join items to categories, and group by on any fields you need from the category table: