2016-07-01 66 views
2

我有兩個不同的數據源組合的大量郵政編碼和區域列表。如果存在重複項,請根據另一列選擇值

我的專欄的樣子: 郵政編碼,領土,源

值可能類似於:

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

我的目標是隻有每一個獨立的郵政編碼一行,如果有一個記錄Source1和Source2中的郵政編碼,始終從Source1中獲取地區。

所以前面的列表會得到簡化爲:

76345, ShiPaTown 
12110, SouthPark 

回答

3

這是一個優先查詢。這裏有一個方法:

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

+0

嗨Giorgos,不幸的是,訪問不支持合併功能 – ChrisG

+1

'IIF(ISNULL(t2.territory),t1.territory,t2.territory)' – shawnt00

+0

@ shawnt00感謝您的更正。 –

1

如果每個源郵政編碼是獨一無二的(儘管它們可能會重疊,但在任何來源中都沒有dups),並且您可以重新合併數據,我會從源1創建表,然後將zip作爲主鍵(不允許dups),然後附加源2中的數據。這是一種手動解決方法,但僅需2秒鐘資源可能是可行的。

相關問題