我想出了一个脚本来选择“主”帐户和“从”帐户。公司名称和邮政编码完全匹配的地方。它认为最近更新的帐户是主帐户。
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'