【问题标题】:Need Oracle SQL Logic For Comparing Data Between Two Tables :: Like VLOOKUP in Excel需要 Oracle SQL 逻辑来比较两个表之间的数据 :: 像 Excel 中的 VLOOKUP
【发布时间】:2021-03-05 02:56:28
【问题描述】:

表1:

Acct Cust Owner Name

1111 A111 PRIM  Dan Jason

1111 B111 SECO  Donna Jason

1111 C111 SECO  July Jason

表2:

Acct Cust Owner Name

2222 B111 PRIM  Donna Jason

2222 C111 SECO  July Jason

2222 DD22 SECO  Jimmy James

我必须将 table1.Cust 字段与 table2.Cust 字段进行比较。如果所有 t1.cust 和 t2.cust 都相同,则可以忽略该记录。如果任何 t1.cust(s) 与 t2.cust(s) 不同,则应报告记录。

在上面的示例中,由于表 1 和表 2 中的一位客户不同(Dan Jason 和 Jimmy James)而所有其他客户都相似,因此我需要报告帐号 1111 和 2222,说明客户不同。

这就像 excel 中的 vlookup。但是,我不确定这在 Oracle 中是否可行。有人可以指导我吗?

【问题讨论】:

    标签: sql oracle union full-outer-join


    【解决方案1】:

    这可能不是最有效的方法,但它很直观。您可以使用MINUS 找到 Table2 中不存在的所有 Table1 条目,然后使用 UNION 该结果集以及 Table1 中不存在的所有 Table2 条目:

    (select Acct, Cust, Owner, Name
       from table1
     MINUS
     select Acct, Cust, Owner, Name
       from table2)
       UNION
    (select Acct, Cust, Owner, Name
       from table2
     MINUS
     select Acct, Cust, Owner, Name
       from table1)
    

    【讨论】:

      【解决方案2】:

      您可以full join,并过滤不匹配的行:

      select 
          coalesce(t1.acct,  t2.acct)  as acct,
          coalesce(t1.cust,  t2.cust)  as cust,
          coalesce(t1.owner, t2.owner) as acct,
          coalesce(t1.name,  t2.name)  as name,
          case when t1.acct is null then 't2' else 't1' end as which
      from table1 t1
      full join t2 
          on  t1.acct  = t2.acct
          and t1.cust  = t2.cust
          and t1.owner = t2.owner
          and t1.name  = t2.name
      where t1.acct is null or t2.acct is null
      

      我在结果集中添加了一个名为which 的列,它指示记录来自哪个表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-06
        • 2018-10-20
        • 1970-01-01
        • 2021-04-23
        • 1970-01-01
        • 2018-06-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多