【问题标题】:Compare data in same table oracle比较同一张表oracle中的数据
【发布时间】:2021-01-28 16:39:00
【问题描述】:

我需要比较同一张表中两个不同 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 来做到这一点,但我不确定如何。

修正—— 项目 a、b 和 c 位于 Id 123 或 Id 789 的 3 个不同记录中。

【问题讨论】:

  • 什么是项目 - 单列,其中值是一个字符串,显示以逗号分隔的项目?如果是这样,似乎这些项目没有任何特定的顺序。顺序是否重要,或者'a,b,c' 是否与'c,a,b' 相同?无论如何,设计数据模型的人都应该被解雇;第一范式在第一个月的任何数据库介绍课程中教授。
  • 当我说项目 a、b、c 时,我的意思是它们是相同 ID 123 的三个不同记录。它实际上不是一个字符串。希望我已经清除了它。

标签: sql oracle join


【解决方案1】:

您可以使用 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 

【讨论】:

  • 当我们将列值与 listagg 组合时,是否有任何大小/长度限制?
【解决方案2】:
ID t1 t2 t3
1 a b c
2 b c a
3 c b a
4 a c b
5 a 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 a b c
5 a b c

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

【讨论】:

    【解决方案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, 'aaa', '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 
    

    结果

    AID BID STATUS
    1 3 same
    2 4 different

    【讨论】:

      猜你喜欢
      • 2020-01-18
      • 2017-04-26
      • 2020-08-12
      • 2015-12-28
      • 1970-01-01
      • 2021-03-15
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多