如果存在重复项,select 基于另一列的值
If duplicates exist, select the value based on another column
我有一个很大的邮政编码和地区列表,是我从两个不同的数据源中合并而来的。
我的专栏如下所示:
邮政编码、地区、来源
值可能如下所示:
76345, ShiPaTown, Source1
76345, ShiPaTown, Source2
12110, South Park, Source1
12110, Mars, Source2
我的 objective 每个唯一邮政编码只有一行,如果在 Source1 和 Source2 中都有一个邮政编码记录,则始终从 Source1 获取领土。
因此之前的列表将缩减为:
76345, ShiPaTown
12110, SouthPark
这是一个优先查询。这是一种方法:
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');
假设每个 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'
如果每个来源中的邮政编码都是唯一的(两个来源中都没有重复项,尽管它们可能重叠)并且您愿意重新合并数据,我会从来源 1 中制作您的 table,然后制作 zip一个主键(不允许重复),然后附加来自源 2 的数据。这是一个手动解决方法,但对于只有 2 个源它可能是可行的。
我有一个很大的邮政编码和地区列表,是我从两个不同的数据源中合并而来的。
我的专栏如下所示: 邮政编码、地区、来源
值可能如下所示:
76345, ShiPaTown, Source1
76345, ShiPaTown, Source2
12110, South Park, Source1
12110, Mars, Source2
我的 objective 每个唯一邮政编码只有一行,如果在 Source1 和 Source2 中都有一个邮政编码记录,则始终从 Source1 获取领土。
因此之前的列表将缩减为:
76345, ShiPaTown
12110, SouthPark
这是一个优先查询。这是一种方法:
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');
假设每个 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'
如果每个来源中的邮政编码都是唯一的(两个来源中都没有重复项,尽管它们可能重叠)并且您愿意重新合并数据,我会从来源 1 中制作您的 table,然后制作 zip一个主键(不允许重复),然后附加来自源 2 的数据。这是一个手动解决方法,但对于只有 2 个源它可能是可行的。