SQL revising table data to a more compact form(SQL 将表数据修改为更紧凑的形式)
问题描述
我有一个表,其中包含如下建模的数据对:
I have a table with data pairs modeled like the following:
Id1 Id2
-----------
100 50
120 70
70 50
34 20
50 40
40 10
Id1 总是比 Id2 大.这些对代表要进行的替换.所以100会被50代替,然后50会被40代替,40会被10代替.
Id1 is always bigger then Id2. The pairs represent replacements to be made. So 100 will be replaced with 50, but then 50 will be replaced with 40, which will then be replaced by 10.
所以结果是这样的:
Id1 Id2
-----------
100 10
120 10
34 20
有没有一种简洁的方式可以改变或加入这张表来表示这一点?
Is there a nice succinct way that I can alter, or join this table to represent this?
我知道我可以加入它本身类似于:
I know i can join it on itself something akin to:
SELECT t1.Id1, t2.Id2
FROM mytable t1
JOIN myTable t2 ON t2.Id1 = t1.Id2
但这需要多次通过,所以我为什么要问是否有更好的方法来完成它?
But this will require several passes, hence why i ask if there is a nicer way to accomplish it?
推荐答案
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 将表数据修改为更紧凑的形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SQL 将表数据修改为更紧凑的形式
基础教程推荐
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
