使用CTE查找Ultimate Parent

时间:2014-11-19 04:21:59

标签: sql-server parent common-table-expression

我明天需要在Production Server(SQL server)中运行一个报告。由于我对CTE不太自信并且需要快速帮助,我在这里提出我的问题。

我有一个像这样的表结构:

表格

UnderLyingConstituentMap
{
ParentUnderLyingId int not null,
UnderLyingId int
}

一个UnderLying可能是多个ParentUnderLying的一部分。所以这是一个多对多的关系。 我获得了一组UnderLyingId s,需要找到所有最终ParentUnderLyingId

可能有一些UnderLying没有父母。然后它们将不存在于此表的UnderLyingId列中。

请帮我解决CTE问题。

2 个答案:

答案 0 :(得分:0)

使用递归连接,如下所示:

WITH UserCTE AS (
  SELECT UnderLyingId ,ParentUnderLyingId 
  FROM dbo.UnderLyingConstituentMap 
  WHERE UnderLyingId = 1

  UNION ALL

  SELECT  UnderLyingId ,ParentUnderLyingId 
  FROM UserCTE AS usr
    INNER JOIN dbo.UnderLyingConstituentMap AS mgr
      ON usr.ParentUnderLyingId = mgr.UnderLyingId 
)
SELECT * FROM UserCTE AS u;

答案 1 :(得分:0)

尝试使用以下查询

;WITH cte1
as
 (
   SELECT ParentUnderLyingId,UnderLyingId, 0 AS level ,
   convert(varchar(100), '<'+convert(varchar(3),UnderLyingId)+'>') as Visited
   FROM #UnderLyingConstituentMap

   UNION ALL

   SELECT T.ParentUnderLyingId,T.UnderLyingId, level +1 ,
   Convert(varchar(100),Visited +'<'+convert(varchar(3),cte1.ParentUnderLyingId)+'>')
   FROM #UnderLyingConstituentMap T 
   INNER JOIN cte1 
   on t.UnderLyingId=cte1.ParentUnderLyingId
   WHERE Visited NOT LIKE ('%<'+convert(varchar(3),t.ParentUnderLyingId)+'>%')
 )
SELECT * FROM cte1
相关问题