我正在尝试使用递归查询来获取每个类别(包括子类别)的事件数。我有 3 个表 - ContentTabs(分层表)、Events 和中间表 RelEventsToContentTabs,所以它是简单的多对多关系。问题是当我使用如下查询时,我得到每个类别的事件数,但没有子类别的事件数。我正在使用 SQL Server 2008。有什么想法吗?
WITH ContentTabsStructure (Id, Name)
AS
(
SELECT Id, Name,parentId FROM ContentTabs
WHERE Id =1
UNION ALL
SELECT ct.Id, ct.Name,ct.parentId FROM ContentTabs AS ct
INNER JOIN ContentTabsStructure AS cts
ON ct.ParentId = cts.Id
)
SELECT cts.id,cts.Name, Count(distinct e.id) as NumberOfEvents
FROM ContentTabsStructure cts
INNER JOIN RelEventsToContentTabs etct
ON cts.id = etct.contentTabId
INNER JOIN Events e
ON etct.eventId = e.id
GROUP BY cts.id,cts.Name