递归 COUNT 查询 (SQL Server)

发布于 2024-09-02 03:43:00 字数 348 浏览 2 评论 0原文

我有两个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

恋你朝朝暮暮 2024-09-09 03:43:00
with /* recursive */ category_tree as (
  select category.id as top_category_id, category.id as category_id
  from category
union all
  select top_category_id, category.id
  from category_tree
       join category on category.idparent = category_tree.category_id
)
select category_tree.top_category_id as category, count(*) as question_count
from category_tree
     join question on question.idcategory = category_tree.category_id
group by category_tree.top_category_id

CTE 构建了每个类别下的子类别列表 - 本质上,它在树中递归并生成(顶级类别、后代类别)的扁平化视图。

初始项(在 union all 之前)选择每个类别,并指示它包含自身 - 然后递归项包括迄今为止找到的类别的所有子类别,并在前一个类别中的所有 Category_id 列时自动停止(不产生结果)迭代是叶类别。

基于此,我们只需将这个扁平化视图连接回问题即可生成一组(顶级类别,问题)行,并基于(顶级类别)进行聚合。

with /* recursive */ category_tree as (
  select category.id as top_category_id, category.id as category_id
  from category
union all
  select top_category_id, category.id
  from category_tree
       join category on category.idparent = category_tree.category_id
)
select category_tree.top_category_id as category, count(*) as question_count
from category_tree
     join question on question.idcategory = category_tree.category_id
group by category_tree.top_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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文