根据列值

时间:2016-02-17 23:36:49

标签: sql tsql

我有一个名为BusinessAssociate的数据库表,为了复杂起见,在该表中有2列

BusinessAssociateKey int
AmalgamatedIntoBAKey int

使用BusinessAssociateKey,我们可以加入其他表,其中一个表(BACorporateStatus)告诉我们BusinessAssociate是活跃的还是合并的。

假设Business Associate密钥123456合并到BA Key 987654中,在同一个表中将有一行,BusinessAssociateKey为987654,这一行也可能合并,例如合并到BusinessAssociateKey 283746。

每个BusinessAssociateKey是否有办法找到活跃的(非合并的)业务伙伴?

链的数量未知,可能是无或可能是n。

编辑:这是一个SQL小提琴,http://sqlfiddle.com/#!9/1e886/1,在此示例中,BusinessAssociateKey 56781未合并,因此对于BusinessAssociateKey 123,幸存/有效BA密钥为56781。

2 个答案:

答案 0 :(得分:0)

自己加入桌子。在这里,我添加了行号以使用自联接获取最后的记录。

   Select  F.Nbr, F.BusinessAssociateKey, F.AmalgamatedIntoBAKey
    From
   (Select row_number() Over(order by (select 1)) as Nbr, E.BusinessAssociateKey, E.AmalgamatedIntoBAKey
    From BusinessAssociate E
   ) F
   LEFT OUTER JOIN
   (Select row_number() Over(order by (select 1)) as Nbr, E.BusinessAssociateKey, E.AmalgamatedIntoBAKey
    From BusinessAssociate E
   ) K
   ON  F.AmalgamatedIntoBAKey = K.BusinessAssociateKey
   where K.Nbr IS  NULL 

http://sqlfiddle.com/#!6/88b53/26

答案 1 :(得分:-1)

递归:

;with rec_cte as(
select b1.BusinessAssociateKey, b1.AmalgamatedIntoBAKey, 1 as rn
  from BusinessAssociate b1 left outer join BusinessAssociate b2 on b1.BusinessAssociateKey = b2.AmalgamatedIntoBAKey
  where b2.BusinessAssociateKey is null
union all
select c.BusinessAssociateKey, b.AmalgamatedIntoBAKey, c.rn + 1
  from rec_cte c inner join BusinessAssociate b on c.AmalgamatedIntoBAKey = b.BusinessAssociateKey
  where b.AmalgamatedIntoBAKey is not null),
cte as(
select BusinessAssociateKey, max(rn) as rn
  from rec_cte
  group by BusinessAssociateKey)

select r.BusinessAssociateKey, r.AmalgamatedIntoBAKey
  from rec_cte r inner join cte c on r.BusinessAssociateKey = c.BusinessAssociateKey and r.rn = c.rn
  option (maxdop 0)