0

我正在尝试使用递归查询来获取每个类别(包括子类别)的事件数。我有 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
4

1 回答 1

0

您还可以在 CTE 中包含 parentId 为:

WITH ContentTabsStructure (Id, Name,parentId)

获取每个类别的子类别,然后在选定的列中包含如下内容以获取子类别的事件数:

, NumberOfSubCatagoryEvents = isnull(
( 
    Count(distinct e.id)
    FROM ContentTabsStructure cts1
    INNER JOIN RelEventsToContentTabs etct1
    ON cts1.id = etct1.contentTabId
    INNER JOIN Events e1
    ON etct1.eventId = e1.id
    where cts1.parentId<cts.parentId
    GROUP BY cts1.id,cts1.Name   

), 0 )
于 2013-10-18T10:51:27.840 回答