SQL script for merging cusotmer accounts
===

I have come up with a script to select the "Master" account and "Slave" account. Where the company name and postal code match exactly. It deems the most recently updated account to be the master.

    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

The issue with the script as it stands is that it may determine that:

 - Account 1 is the master and a duplicate slave Account 2 exists.
 - Account 1 is the master and a duplicate slave Account 3 exists.
 - Account 2 is the master and a duplicate slave Account 3 exists.

As you can see the result of each step would impact the following step. Can you recommend a smarter query?