小编典典

SQL将表数据修改为更紧凑的形式

sql

我有一个表,其数据对的建模如下:

Id1    Id2
-----------
100    50
120    70
70     50
34     20
50     40
40     10

Id1然后总是更大Id2。这些对表示要进行的替换
。因此,将100替换为50,然后将50替换为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

但是,这需要多次通过,因此,为什么我问是否有更好的方法
来完成它?


阅读 222

收藏
2021-03-08

共1个答案

小编典典

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

Result:

id1         id2
----------- -----------
34          20
100         10
120         10
2021-03-08