我有一个表,其中包含如下建模的数据对:
Id1 Id2
-----------
100 50
120 70
70 50
34 20
50 40
40 10
Id1
总是比 Id2
大。这些对代表要进行的替换。所以 100 将被替换为 50,但随后 50 将被替换为 40,然后 40 将被替换为 10。
所以结果是这样的:
Id1 Id2
-----------
100 10
120 10
34 20
有没有一种我可以更改或加入此表来表示的简洁明了的方式?
我知道我可以加入它本身类似于:
SELECT t1.Id1, t2.Id2
FROM mytable t1
JOIN myTable t2 ON t2.Id1 = t1.Id2
但这将需要多次通过,因此我为什么要问是否有更好的方法来完成它?
最佳答案
declare @t table(Id1 int, Id2 int)
insert @t values (100, 50)
insert @t values ( 120, 70)
insert @t values ( 70, 50)
insert @t values ( 34, 20)
insert @t values ( 50, 40)
insert @t values ( 40, 10)
;with a as
(
-- find all rows without parent <*>
select id2, id1 from @t t where not exists (select 1 from @t where t.id1 = id2)
union all -- recusive work down to lowest child while storing the parent id1
select t.id2 , a.id1
from a
join @t t on a.id2 = t.id1
)
-- show the lowest child for each row found in <*>
select id1, min(id2) id2 from a
group by id1
结果:
id1 id2
----------- -----------
34 20
100 10
120 10
关于SQL 将表数据修改为更紧凑的形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9764915/