SQL-递归地在另一个表中查找计数

时间:2018-11-28 12:50:53

标签: sql sql-server

我有一个同时包含类别和子类别的表:

CategoryID     CategoryName  ParentCategoryID
   1              CatA           NULL
   2              CatA1           1
   3              CatA2           1
   4              CatA3           1
   5              CatB           NULL
   6              CatB1           5
   7              CatC           NULL
   8              CatC1           7

我还有另一个有映射的表

MappingID     CategoryID     ItemID
   1              2            1
   2              3            1
   3              6            2
   4              8            3
   5              2            3
   6              3            4
   7              4            4
   8              2            3
   9              3            4
   10              2            2
   11              2            2
   12              2            2
   13              2            3
   14              2            1

我需要一个结果集,其中显示每个类别的所有项目的计数,例如:

Category    No. of Items
   1            12
   5            1
   7            1

有人可以指导我吗?

我尝试使用CTE:

WITH CTE (CategoryID, CategoryName, ParentID, CategoryParentName)
AS
(
    SELECT      CategoryID,
                CategoryName,
                ParentCategoryID,
                CategoryName AS CategoryParentName
    FROM        [dbo].[Category]
    WHERE       ParentCategoryID IS NULL
    AND         IsDeleted = 0

    UNION ALL

    SELECT      garages.CategoryID,
                garages.CategoryName,
                garages.ParentCategoryID,
                traces.CategoryName AS CategoryParentName
    FROM        [dbo].[Category] AS garages
    INNER JOIN  CTE AS traces  ON traces.CategoryID= garages.ParentCategoryID
)

SELECT          gr.CategoryID, COUNT(map.CategoryID) AS Total
FROM            CTE gr
INNER JOIN      [dbo].[CategoryMapping] map ON gr.CategoryID = map.CategoryID
GROUP BY        gr.CategoryID

1 个答案:

答案 0 :(得分:0)

如果类别只有两个级别,则不需要递归查询

select coalesce(c.ParentCategoryID, c.CategoryID), count(*)
from Category c
join CategoryMapping m on c.CategoryID = m.CategoryID 
group by coalesce(c.ParentCategoryID, c.CategoryID)

很明显,没有映射的类别将不存在。