1

想象一个名为 的表Group,每个组都可以有“子”组,只要它们的“级别”较低。所以表之间是一对多的关系Group and childGroup

在此处输入图像描述

和之间还有一个many-to-many关系GroupItems所以Groups_Items用来保存每个表的FK。

我需要编写一个查询,对于 a given Group key,我应该对、 和 all进行find all its child分组。all the childs of child groupsthe customers belonging to those found groups

我知道它需要是某种递归查询,但我不知道如何在 SQL 中完成。以下是讨论的表的结构:

在此处输入图像描述

所以如果我在上表中有这些数据集:

在此处输入图像描述

查询是 find For Group 1, find Its customers, Its Child groups (and their Childs) and all their customers,输出应该是:

<Group> 1
    <customer> 1
    <customer> 2
    <Group> 2
        <customer> 2
        <Group> 3
        <Group> 4

有人可以告诉我如何做到这一点吗?谢谢

4

1 回答 1

2

我希望我理解你的问题

;WITH Hierarchy (GroupID,ID,  ParentID
               ,hLevel
               ) AS
(
   -- Base case
   (
   Select  [Parent Key] as GroupID,NULL,NULL,0
   FROM Tree
   where [Parent Key]=1
   UNION
   SELECT
      [Child Key] as GroupID,
      [Child Key] as ID,
      [Parent Key] as ParentID
      ,1 as hLevel
   FROM Tree
   where [Parent Key]=1
   ) 

   UNION ALL

   -- Recursive step
   SELECT
      e.[Child Key] as GroupID,
      e.[Child Key],
      e.[Parent Key]
     ,eh.hLevel + 1
   FROM tree e
      INNER JOIN Hierarchy eh ON
         e.[Parent Key] = eh.ID
)


Select Distinct h.GroupID, c.Name,h.ParentID as ParentGroupID
from Hierarchy h
left join test c on h.GroupID=c.ID

较旧的尝试是

Declare @Parent int
Declare @count int
Select @Parent=??

Select cast(ID as Int) as ID
into #tmp
from Tabelle where ParentID=@Parent

select @Count=0
While @Count<(Select Count(*) from #tmp)
   begin
   Select @Count=(Select Count(*) from #tmp)
   insert into #tmp Select Cast(ID as int) from Tabelle where ParentID in (Select ID from #tmp) and ID not in (Select ID from #tmp)
   end
Select * from #tmp
Drop table #tmp
于 2012-11-11T00:21:06.993 回答