【问题标题】:compare multiple columns of 2 tables which some columns having comma separated values in oracle比较 2 个表的多个列,其中一些列在 oracle 中具有逗号分隔值
【发布时间】:2020-09-20 11:49:21
【问题描述】:

我有 2 个如下表

表 A:

表 B:

我想比较两个表的列和预期的输出。

条件:

1)所有列值应匹配(一列的逗号分隔值中至少一个值)

例子:

如果我们从第二个表中取 cbn100(cf1,cf2,cf3 列值) 与第一个表 M1001 (cf1,cf2,cf3 列值) 进行比较

  1. M1001.cf1 (co1) = cbn100.cf1 (co1) - 真

  2. M1001.cf2 (co2,co3) = cbn100.cf2 (co2) - true(至少 1 (co2) 值匹配)

  3. M1001.cf3 (co4) = cbn100.cf3 (co4) - 真

因此所有值都匹配,输出应该是 M1001=cbn100

2)如果空值与非空值比较,则条件为真

例子:

如果我们从第二张表中取出 cbn103 值并与第一张表中的 m1002 进行比较

  1. M1002 (null) = cbn103.cf1(co1) - 真
  2. M1002 (null) = cbn103.cf1(co5) - 真
  3. M1002 (co7) = cbn103.cf3(co7,co4) - 真

因此所有条件匹配输出应该是 M1002=cbn103

预期输出:

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    尝试这样的事情(可能需要调整,仅使用您的数据集进行测试):

    select result_
    from (
      select 
        case when
          ( AB1 = 'true' and AB2 = 'true' and AB3 = 'true' )  
          or
          ( BA1 = 'true' and BA2 = 'true' and BA3 = 'true' )  
          then mfpartno || '=' || cbn
        end result_
      from (
        select
          A.mfpartno
        , B.cbn
        , case when instr( A.cf1, B.cf1 ) > 0 or B.cf1 is null then 'true' else 'false' end AB1
        , case when instr( A.cf2, B.cf2 ) > 0 or B.cf2 is null then 'true' else 'false' end AB2
        , case when instr( A.cf3, B.cf3 ) > 0 or B.cf3 is null then 'true' else 'false' end AB3
        , case when instr( B.cf1, A.cf1 ) > 0 or A.cf1 is null then 'true' else 'false' end BA1
        , case when instr( B.cf2, A.cf2 ) > 0 or A.cf2 is null then 'true' else 'false' end BA2
        , case when instr( B.cf3, A.cf3 ) > 0 or A.cf3 is null then 'true' else 'false' end BA3
        from tablea A cross join tableb B
      )
    )
    where result_ is not null
    ;
    

    结果

            RESULT_ 
    _______________ 
    M1001=cbn100    
    M1002=cbn103 
    

    解释

    内部查询使用 CROSS JOIN,它允许我们比较所有可能的行组合。 INSTR() 用于检测 tableA 的字符串是否包含 tableB 的字符串(反之亦然)。还有一个条件可以根据您的要求处理 NULL。如果我们得到 3 个“真”结果,那么就找到了一个“匹配”。 DBfiddle here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-29
      • 1970-01-01
      • 2020-02-01
      • 2014-03-16
      • 2010-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多