我已經想出了一個腳本來選擇「主」帳戶和「從」帳戶。公司名稱和郵政編碼完全匹配。它認爲最近更新的帳戶是主人。用於合併客戶帳戶的SQL腳本
select
m.ev870_acct_code, m.ev870_company_name, m.ev870_postal_code, m.ev870_iacvb_code,
s.ev870_acct_code, s.ev870_company_name, s.ev870_postal_code, s.ev870_iacvb_code
from
ev870_acct_master m
inner join
ev870_acct_master s
on
m.ev870_company_name = s.ev870_company_name
and m.ev870_postal_code = s.ev870_postal_code
and m.ev870_upd_stamp > s.ev870_upd_stamp
where
m.ev870_class = 'o'
and s.ev870_class = 'o'
and m.ev870_status != '0'
and s.ev870_status != '0'
and (m.ev870_iacvb_code = s.ev870_iacvb_code or isnull(m.ev870_iacvb_code,'') = '' or isnull(s.ev870_iacvb_code,'') = '')
and s.ev870_company_name like '%council%'
order by
m.ev870_upd_stamp desc
用,因爲它代表了腳本的問題是,它可以判斷:
- 賬戶1是主副本從賬戶2存在。
- 賬戶1是主賬戶,存在重複的從賬戶3。
- 賬戶2是主賬戶,存在重複的從賬戶3。
正如你所看到的,每一步的結果都會影響下一步。你能推薦一個更聰明的查詢嗎?
編輯解決方案:
select
m.ev870_acct_code, m.ev870_company_name, m.ev870_postal_code, m.ev870_iacvb_code,
s.ev870_acct_code, s.ev870_company_name, s.ev870_postal_code, s.ev870_iacvb_code
from
ev870_acct_master s
inner join
(
select
ev870_acct_code, ev870_company_name, ev870_postal_code, ev870_iacvb_code, ev870_upd_stamp
,row_number() over (partition by ev870_company_name, ev870_postal_code, ev870_iacvb_code order by ev870_upd_stamp desc) as howRecent
from
ev870_acct_master
where
ev870_class = 'o'
and ev870_status != '0'
and ev870_postal_code != ''
and ev870_company_name like 'A%'
) m
on
m.ev870_company_name = s.ev870_company_name
and m.ev870_postal_code = s.ev870_postal_code
and m.ev870_upd_stamp > s.ev870_upd_stamp
where
m.howRecent = 1
and m.ev870_iacvb_code = s.ev870_iacvb_code
and s.ev870_class = 'o'
and s.ev870_status != '0'
你在什麼版本的SQL Server? – iruvar 2012-07-24 14:22:20
@Lee你能解釋一下你試圖用這個查詢完成什麼嗎? – kristof 2012-07-24 14:24:49
SQL Server 2005. @kristof我在我的應用程序中識別重複的帳戶,然後將合併到一個帳戶。 – 2012-07-24 14:28:16