0

我有兩個表如下SQL Server 2008的父子表使用CTE與其他數據

Group 
Id, Name,  ParentId 
1, North,  NULL 
2, South,  NULL 
3, London,  2 
4, Brighton, 2 
5, Fulham,  3 
6, SuperStores, NULL 

StoreAndGroup 
Id, StoreId,  GroupId 
1, 41,   2 
2, 52,   3 
3, 88,   5 
4, 88,   6 
5, 41,   6 

我想製作一個表格,顯示屬於每個組的所有門店(包括亞組),所以上述將成爲

GroupId, StoreId 
2,  41 
2,  52 
2,  88 
3,  52 
3,  88 
5,  88 
6,  88 
6,  41 

我可以使用遞歸CTE給我看一個特定組的所有孩子,但我有點堅持以如何把額外的數據。

回答

0

其實這原來是一個簡單連接

WITH 
    cteGroups (Id, GroupName, ParentGroupId, GroupLevel) 
    AS 
    (
    SELECT Id, GroupName, ParentGroupId 
    FROM Dim_Group 
    UNION ALL 
    SELECT g.Id, g.GroupName, g.ParentGroupId 
    FROM Dim_Group g 
     INNER JOIN cteGroups cg 
     ON g.ParentGroupId = cg.Id 
) 

    select * from cteGroups inner join dim_groupmember on cteGroups.Id = dim_groupmember.groupid 

達倫

0

也許你可以這樣做:

SELECT GroupId, StoreId 
FROM StoresAndGroup 
UNION ALL 
SELECT ParentId AS GroupId, StoreId 
FROM StoresAndGroup s INNER JOIN [Group] g ON g.GroupId = s.GroupId 
WHERE g.ParentId IS NOT NULL