我有两个MS SQL表:Category,Question。每个问题都分配给一个类别。一个类别可能有许多子类别。
如何递归计算给定类别的所有问题(包括子类别中的问题)。我已经尝试过基于几个教程,但仍然无法弄明白:(
答案 0 :(得分:3)
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列时自动停止(不产生结果)在上一次迭代中是叶子类别。
基于此,我们只是简单地将这个展平视图连接到问题上以生成一组(顶部类别,问题)行,并基于(顶部类别)聚合。