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

标签 sql sql-server sql-server-2008 tsql

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

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/

相关文章:

sql-server - Sql ChangeTracking 清理表

php - 如何使用PHP和SQL删除行

mysql - WebMatrix 错误 "The specified password for user account ' 根无效...”

mysql - 如何在不切割特定列的情况下对sql表进行分页

c# - 错误 : 40 - Could not open a connection to SQL Server

c# - 如何在异常发生之前检测到导致异常的条件?

sql - 为父级及其子级分配相同的 SNo

sql - 通过删除执行计划中的排序运算符来优化 SQL 查询

sql:如何改进这条语句

mysql - SQL UPDATE 语句中涉及子查询的错误