程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了比较同表oracle中的数据大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决比较同表Oracle中的数据?

开发过程中遇到比较同表Oracle中的数据的问题如何解决?下面主要结合日常开发的经验,给出你关于比较同表Oracle中的数据的解决方法建议,希望对你解决比较同表Oracle中的数据有所启发或帮助;

我需要比较同一个表中两个不同 ID 之间的数据。

例如)ID 123 可以包含项目 a,b,c
ID 234 可以有项目 x,a,b
并且 ID 789 可以有项目 a、b、c。

我的sql应该可以根据items列说ID 123和ID 789相同,或者根据item列说ID 123或ID 234不同。

我想我们可以在 Oracle 中使用 self join 来做到这一点,但我不确定如何。

更正—— 对于 ID 123 或 ID 789,项目 a、b、c 位于 3 个不同的记录中。

解决方法

设置

create table T1 (id number(10),x nvarchar2(10),y nvarchar2(10));
insert into T1 values(1,'aaa','bbb');
insert into T1 values(2,'xxx','xxx');
insert into T1 values(3,'bbb');
insert into T1 values(4,'ccc','ccc');

打电话

select a.id aid,b.id bid,'same' status  -- all items with matching fields
from 
  (SELEct 'fakEID123' fakEID,t.* FROM t1 t where id = 1) a inner join 
  (SELEct 'fakEID123' fakEID,t.* FROM t1 t where id = 3) b on a.fakEID = b.fakEID
where a.x = b.x and a.y = b.y 
union all
select a.id,b.id,'different' status -- union with all items with not matching fields
from 
  (SELEct 'fakEID123' fakEID,t.* FROM t1 t where id = 2) a inner join 
  (SELEct 'fakEID123' fakEID,t.* FROM t1 t where id = 4) b on a.fakEID = b.fakEID
where a.x <> b.x and a.y <> b.y 

结果

援助 出价 状态
1 3 相同
2 4 不同
,

您可以使用 cte 并将每条记录与所有其他记录连接起来进行比较,如下所示:

With cte as
(SELEct id,listagg(item,',') within group (order by item) as items
   From your_table t
  Group by id)
SELEct t1.id,t2.id,Case when t1.items = t2.items then 'match' else 'do not match' end as res_
 From cte t1 join cte t2 on t1.id < t2.id 
,
ID t1 t2 t3
1 b c
2 b c
3 c b
4 c b
5 b c
SELEct t1.*
  from table t1
  join table t2
    on t1.id != t2.id 
   and t1.t1 = t2.t1
   and t1.t2 = t2.t2
   and t1.t3 = t2.t3

数据输出

ID t1 t2 t3
1 b c
5 b c

重要的是表本身连接并且 ID 不同,以免评估相同的记录。

大佬总结

以上是大佬教程为你收集整理的比较同表oracle中的数据全部内容,希望文章能够帮你解决比较同表oracle中的数据所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: