递归 COUNT 查询 (SQL Server)
我有两个 MS SQL 表:类别、问题。每个问题都被分配到一个类别。一个类别可以有多个子类别。
类别
- ID:bigint (PK)
- 名称:nvarchar(255)
- 接受问题:位
- IdParent:bigint (FK)
问题
- ID:bigint (PK)
- 标题:nvarchar(255) ...
- IdCategory : bigint (FK)
如何递归计算给定类别的所有问题(包括子类别中的问题)。我已经根据几个教程尝试过,但仍然无法弄清楚:(
I've two MS SQL tables: Category, Question. Each Question is assigned to exactly one Category. One Category may have many subcategories.
Category
- Id : bigint (PK)
- Name : nvarchar(255)
- AcceptQuestions : bit
- IdParent : bigint (FK)
Question
- Id : bigint (PK)
- Title : nvarchar(255)
... - IdCategory : bigint (FK)
How do I recursively count all Questions for a given Category (including questions in subcategories). I've tried it already based on several tutorials but still can't figure it out :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CTE 构建了每个类别下的子类别列表 - 本质上,它在树中递归并生成(顶级类别、后代类别)的扁平化视图。
初始项(在 union all 之前)选择每个类别,并指示它包含自身 - 然后递归项包括迄今为止找到的类别的所有子类别,并在前一个类别中的所有 Category_id 列时自动停止(不产生结果)迭代是叶类别。
基于此,我们只需将这个扁平化视图连接回问题即可生成一组(顶级类别,问题)行,并基于(顶级类别)进行聚合。
The CTE builds a list of which subcategories are under each category- essentially, it recurses through the tree and produces a flattened view of (top category, descendant category).
The initial term (before the union all) selects each category, and indicates that it contains itself- the recursive term then includes all the subcategories for categories found so far, and stops (produces no results) automatically when all the category_id columns in the previous iteration were leaf categories.
Based on that, we simply join this flattened view back onto question to produce a set of (top category, question) rows, and aggregate based on (top category).