【问题标题】:If duplicates exist, select the value based on another column如果存在重复,请根据另一列选择值
【发布时间】:2016-07-01 15:36:48
【问题描述】:

我有一个大的邮政编码和地区列表,我从两个不同的数据源合并。

我的专栏如下所示: 邮政编码、地区、来源

这些值可能如下所示:

76345, ShiPaTown, Source1
76345, ShiPaTown, Source2
12110, South Park, Source1
12110, Mars, Source2

我的目标是每个唯一邮政编码只有一行,并且如果在 Source1 和 Source2 中都有邮政编码的记录,则始终从 Source1 获取领土。

所以之前的列表将简化为:

76345, ShiPaTown
12110, SouthPark

【问题讨论】:

    标签: sql ms-access ms-access-2013


    【解决方案1】:

    这是一个优先级查询。这是一种方法:

    select zip, town
    from t
    where source = 'source1'
    union all
    select zip, town
    from t
    where source = 'source2' and
          not exists (select 1 from t as t2 where t2.zip = t.zip and t2.source = 'source1');
    

    【讨论】:

      【解决方案2】:

      假设每个zipcode 有两条或一条记录,那么您可以使用以下查询:

      SELECT t1.zipcode, 
             IIF(ISNULL(t2.territory), t1.territory, t2.territory) AS territory,
             IIF(ISNULL(t2.source), t1.source, t2.source) AS source
      FROM mytable AS t1
      LEFT JOIN (
         SELECT zipcode, territory, source
         FROM mytable
         WHERE source = 'Source1') AS t2 ON t1.zipcode = t2.zipcode
      WHERE t1.source <> 'Source1'
      

      Demo here

      【讨论】:

      • 您好 Giorgos,很遗憾 Access 不支持合并功能
      • IIF(ISNULL(t2.territory), t1.territory, t2.territory)
      【解决方案3】:

      如果每个来源中的邮政编码是唯一的(两个来源中没有重复,尽管它们可能重叠)并且您愿意重新整合数据,我会从来源 1 制作您的表格,然后将 zip 设为主键(没有重复允许),然后附加来自源 2 的数据。这是一种手动解决方法,但只有 2 个源可能可行。

      【讨论】:

        猜你喜欢
        • 2016-02-23
        • 1970-01-01
        • 2021-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-29
        • 1970-01-01
        • 2018-08-16
        相关资源
        最近更新 更多