在关系中获得孩子的数量

时间:2016-04-18 19:11:13

标签: sql sql-server tsql common-table-expression recursive-query

我有2个表,一个用于 Ticketcategories

CAT_PK, CAT_FK, CAT_Name

其中CAT_FK指向表中作为父类别的另一个类别,并且为null,该类别没有父类。

门票

TIC_PK,CAT_FK

CAT_FK指向票证属于的类别。票证只能有一个类别。

按每个类别计算门票数量很容易,但我需要做的是获取一个类别的门票数量,包括属于该类别孩子的所有门票。

所以,如果存在这种类似的情况:

Stuff
>Blue Stuff
>Red Stuff
>Yellow Stuff
  >Yellow Spotted Stuff

获取Stuff的门票数量还包括计数中所有子类别下的门票。

我一直在使用递归CTE作为解决方案,但由于计数和群组的性质,我不确定它是否有能力:

With
TicketCTE (count,CAT_PK,CAT_FK_Parent, CAT_Description)
as
(
Select Count(*) as count,CAT_PK,CAT_FK_Parent, CAT_Description
from Tickets
JOIN TicketCategories
ON TIC_CAT_FK = CAT_PK
GROUP BY CAT_PK,CAT_FK_Parent,CAT_Description

union all

Select Count(*) as count,TicketCategories.CAT_PK,TicketCategories.CAT_FK_Parent, TicketCategories.CAT_Description
from Tickets
join TicketCategories
on TIC_CAT_FK = TicketCategories.CAT_PK
join TicketCTE
on TicketCategories.CAT_PK = TicketCTE.CAT_PK
GROUP BY TicketCategories.CAT_PK,TicketCategories.CAT_FK_Parent,TicketCategories.CAT_Description
)
Select TicketCTE.*
from TicketCTE
left join TicketCTE MgrCTE
on TicketCTE.CAT_FK_Parent = MgrCTE.CAT_PK

由于我得到错误,不确定这是否可能,

  

递归公用表表达式的递归部分中不允许使用GROUP BY,HAVING或聚合函数

1 个答案:

答案 0 :(得分:1)

你应该试试这个:

;WITH categorylevel AS (
    SELECT 
       CAT_PK, CAT_Name,CAT_PK AS TopC 
    FROM TicketCategories
    WHERE CAT_FK IS NULL

    UNION ALL

    SELECT C.CAT_PK, C.CAT_Name,C2.TopC AS TopC
    FROM TicketCategories C
    INNER JOIN categorylevel C2 ON C.CAT_FK = C2.CAT_PK
)
SELECT TopC, Count(*) FROM categorylevel JOIN  Tickets
ON TIC_CAT_FK = CAT_PK
GROUP BY TopC

See Demo here