获得特定孩子的父母和父母

时间:2015-06-15 10:38:41

标签: sql-server sql-server-2005 sql-cte

我有如下表格

tablename:ChildID ChildCommonID ParentID 1 2 0 2 3 0 3 4 1 4 5 3 5 6 4

ChildID= 5

问题是:

我有一个孩子ID示例:ChildID 5 4 3 1

所以如果它包含父母,我需要检查它是否有父母 然后检查相应的parentid,在这种情况下,parentID是4所以需要检查 孩子4有任何父母,在这种情况下,孩子4的父母ID是3,所以获得支票子3有任何父母 在这种情况下,孩子3有父1,所以检查孩子1有任何父母在这里孩子1是最大的父母,它没有父母所以停止过程 并将所有子项最多返回1

此处的预期输出为

with getallparent as (
   select * 
   from ExampleTable 
   where ChildID  = 5 
  union all 
  select *
   from ExampleTable c 
     Left join getallparent p on p.ChildID = c.ParentID 
) 
select *
from getallparent;

我尝试了类似下面的内容,但它没有提供正确的输出

create table ExampleTable(ChildID int,ChildCommonID int ,ParentID int )
insert into ExampleTable values(1,2,0)
insert into ExampleTable values(2,3,0)
insert into ExampleTable values(3,4,1)
insert into ExampleTable values(4,5,3)
insert into ExampleTable values(5,6,4)

如果您需要样本数据,可以使用以下查询

SELECT  SUM(COALESCE(sr.Income, 0)) AS Income,
        SUM(i.repairCharge) AS Labour,
        SUM(i.shippingCharge) AS Carriage
FROM    Invoices AS i
        LEFT JOIN
        (   SELECT  InvNo, SUM((price-discount)*quantity) AS Income
            FROM    SalesRecords
            GROUP BY InvNo
        ) AS sr
            ON sr.InvNo = i.ID
WHERE   i.dateTime BETWEEN 1434326474 AND 1434361694;

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:3)

与我的评论一样,您的列在加入时不正确。使用getallparent p on p.ParentID = c.ChildID

with getallparent as (
   select ChildID,ParentID
   from ExampleTable 
   where ChildID  = 5 
  union all 
  select C.ChildID,C.ParentID
   from ExampleTable c 
     inner join getallparent p on p.ParentID = c.ChildID 
) 
select *
from getallparent;

Fiddle