【问题标题】:Filter out identical rows od data based on mutliple criteria to only show outliers根据多个条件过滤掉相同的数据行以仅显示异常值
【发布时间】:2020-03-19 15:04:24
【问题描述】:

我正在创建一个要返回特定结果集的存储过程

我有 2 个数据集试图以某种方式加入,以便它只返回异常记录(没有匹配项)。我曾考虑过使用 UNION 和 EXCEPT,但它似乎不适用于这种情况。为了让这不那么复杂,我目前在我的 proc 中有两个 CTE(或者我可以使用#TempTables)。

查询结果 1. 在下面的结果集中,这个查询将返回 3 个字段。此处的 Field3 文本值将始终相同。

 Field1         Field2        Field3
 123            BAK           'Missing in Query 2'
 234            HAO           'Missing in Query 2'
 345            OPP           'Missing in Query 2'

查询结果 2. 此处同样成交,Field3 将始终具有相同的文本值。

 Field1         Field2        Field3
 123            BAK           'Missing in Query 1'
 234            HAO           'Missing in Query 1'
 678            UTO           'Missing in Query 1'

期望的结果:这两个返回第一行(字段 345)的原因是查询 2 中缺少,而查询 1 中缺少第二行。我只查找 Query1.Field1=Query2 的匹配项。 Field1 和 Query1.Field2 = Query2.Field2。

  Field1         Field2        Field3
  345            OPP           'Missing in Query 2'   <- from Query 1
  678            UTO           'Missing in Query 1'   <- from Query 2

我尝试使用 FULL JOIN 来执行此操作,但 FULL JOIN 会返回另外 3 列具有 NULL 值的列。我试图避免这种情况,只显示如上所示的结果。任何帮助将不胜感激。

【问题讨论】:

    标签: sql sql-server ssms-2012


    【解决方案1】:

    我认为您想要两个表中都不存在的行。一种方法是:

    select qr1.*
    from qr1
    where not exists (select 1 from qr2 where qr2.field1 = qr1.field1 and qr2.field2 = qr1.field2)
    union all
    select qr2.*
    from qr2
    where not exists (select 1 from qr1 where qr1.field1 = qr2.field1 and qr1.field2 = qr2.field2);
    

    【讨论】:

      【解决方案2】:

      你可以使用full outer join

      select coalesce(qr1.field1, qr2.field1) as field1,
             coalesce(qr1.field2, qr2.field2) as field2,
             (case when qr1.field1 is null 
                   then 'Missing in Query 1'
                   else 'Missing in Query 2'  
              end) as Field3
      from qr1 full outer join
           qr2
           on qr1.field1 = qr2.field1 and qr1.field2 = qr2.field2
      where (qr1.field1 is null or qr2.field2 is null);
      

      【讨论】:

        猜你喜欢
        • 2021-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-07
        • 1970-01-01
        • 2022-12-09
        • 1970-01-01
        相关资源
        最近更新 更多