【问题标题】:SQL query to show the most complete matching records as belowSQL查询显示最完整的匹配记录如下
【发布时间】:2018-10-18 17:56:20
【问题描述】:

我想要一个显示最完整匹配记录的查询,如下所示。我正在使用 MS Access,但如果没有访问解决方案,ANSI SQL 或 Oracle 答案就可以了。

  • col2 是唯一一个不可为空的列,但是从结果可以看出,col2 中可能有多个相同值的记录返回
  • 如您所见,在合并记录以生成结果时会忽略空值。

表 1

col1    col2    col3    col4
---------------------------------
c       d               g       
c       d        
        d               g
d       e       g       
d       e        
        e       g
e       e       g       
e       e        
        e       g
e       f
        g       h

查询结果

col1    col2    col3    col4
---------------------------------
c       d               g
d       e       g       
e       e       g       
e       f
        g       h               

感谢您的尝试,但经过进一步调查,我发现使用“加入”和“不存在”的两种建议解决方案都有一个错误。

建议的“加入”解决方案中的错误 有一个如下所示的错误,其中两行在建议中变成了 4

col1 col2 col3 col4

    d       g       i                
    d       h       j

查询结果

col1 col2 col3 col4

    d       g       i                
    d       g       j
    d       h       i                
    d       h       j

建议的“不存在”解决方案中的错误

通过添加右括号修复查询后,我能够运行“不存在”解决方案。在 col2 上匹配但在 col3 上不匹配的两行合并为一行。它们有不同的数据,应该是唯一的

col1 col2 col3 col4 --------------------------------- 我 d h 查询结果 col1 col2 col3 col4 --------------------------------- 我

【问题讨论】:

  • 在您的示例中,返回的行始终是原始行之一。总是这样吗?
  • “最完整”是否也可以说“包含数据值的列最多的行”?
  • Gordon - 它不必是原始行之一。 Jacob H- 你可以说“包含数据值的列最多的行”

标签: sql ms-access-2010


【解决方案1】:

对于您的示例数据,这应该有效:

select t1.col1, t2.col2, t3.col3, t4.col4
from (((select distinct col2 from t) as t2 left join
       (select distinct col2, col1 from t where col1 is not null) as t1
       on t1.col2 = t2.col2
      ) left join
      (select distinct col2, col3 from t where col3 is not null) as t3
      on t3.col2 = t2.col2
     ) left join
     (select distinct col2, col4 from t where col4 is not null) as t4
     on t4.col2 = t2.col2;

如果结果集中的行总是在原始数据中,那么not exists 有效:

select t.*
from t
where not exists (select 1
                  from t as t2
                  where t2.col2 = t.col2 and
                        (t2.col1 is not null and t.col1 is null or
                         t2.col3 is not null and t.col3 is null or
                         t2.col4 is not null and t.col4 is null
                 );

【讨论】:

  • 非常感谢戈登。我以为我很了解 sql,但我永远不会得到这个,尤其是因为网上没有例子。
  • 感谢您尝试 Gordon,但您提供的两个查询存在问题
  • 我已经提供了上面两个建议解决方案的错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-08
  • 1970-01-01
  • 2012-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多