0

SQL Server 2008の親、子テーブル

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 

など

を次のように私は2つのテーブルを持って、私はサブグループを含む各グループに属するすべての店舗を示す(表を作成したいです上記

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