TSQL - 查询以获取与每个类别和子类别关联的项目数
我有以下表格:
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
请记住,这不是一个 n 级层次结构,类别只有 2 级,因此没有类别的 ParentID 可以为 2。
我正在寻找的是一种返回类别的方法,并带有一个额外的列,该列显示该类别拥有的项目数量(包括其子类别)。
即我正在寻找一个可以返回类似以下内容的查询(或过程):
Categories
============================================
CategoryID | ParentID | Text | Count
--------------------------------------------
1 NULL Text 3
2 1 Text 1
3 NULL Text 1
4 1 Text 1
我当前获取与类别关联的项目的方法如下(给定类别ID,@CategoryID):
SELECT * FROM Items
WHERE CategoryID
IN (SELECT CategoryID FROM Categories where ParentID = @CategoryID or CategoryID = @CategoryID)
我的问题是我不能似乎将其链接到类别本身的选择查询。 这可能非常简单,但我尝试过使用 CTE 和各种 group by 子句的方法,但类别的层次结构似乎使我的逻辑失去了意义。
感谢您的帮助!
编辑:查询还需要考虑没有与其关联的项目的类别
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须将项目加入类别,并根据类别表中所需的任何字段进行分组:
You'd have to join items to categories, and group by on any fields you need from the category table: