I am importing customer data from a another vendor's system and we have merge processes that we use to identify potential duplicate customer accounts and them merge them if they meet certain criteria - like same first name, last name, SSN and DOB. In this process, I am seeing where we are creating chains - for instance, Customer A is merged to Customer B who is then merged to Customer C.
What I am hoping to do it to identify these chains and update the customer record to point to the last record in the chain. So in my example above, Customer A and Customer B would both have Customer C's id in their merged To field.
CustID FName LName CustStatusType isMerged MergedTo
1 Kevin Smith M 1 2
2 Kevin Smith M 1 3
3 Kevin Smith M 1 4
4 Kevin Smith O 0 NULL
5 Mary Jones O 0 NULL
6 Wyatt Earp M 1 7
7 Wyatt Earp O 1 NULL
8 Bruce Wayn M 1 10
9 Brice Wayne M 1 10
10 Bruce Wane M 1 11
11 Bruce Wayne O 1 NULL
CustStatusType indicates if the customer account is open ("O") or merged ("M"). And then we have an isMerged field as a BIT field that indicates whether the account has been merged and finally the MergedTo field that indicates what customer account the record was merged to.
With the example provided, what I would like to achieve would to have the CustID records of 1 & 2 have their MergedTo record set to 3 - while CustID 3 could either be updated or left as is. For Cust IDs 4, 5, and 6 - these records are find and do not need to be updated. But on Cust IDs 8 - 10, I would like these records to be set to 11 - like the table below.
CustID FName LName CustStatusType isMerged MergedTo
1 Kevin Smith M 1 4
2 Kevin Smith M 1 4
3 Kevin Smith M 1 4
4 Kevin Smith O 0 NULL
5 Mary Jones O 0 NULL
6 Wyatt Earp M 1 7
7 Wyatt Earp O 1 NULL
8 Bruce Wayn M 1 11
9 Brice Wayne M 1 11
10 Bruce Wane M 1 11
11 Bruce Wayne O 1 NULL
I haven't been able to figure out how to achieve this with TSQL - suggestions?
Test Data:
DROP TABLE IF EXISTS #Customers;
CREATE TABLE #Customers
(
CustomerID INT ,
FirstName VARCHAR (25) ,
LastName VARCHAR (25) ,
CustomerStatusTypeID VARCHAR (1) ,
isMerged BIT ,
MergedTo INT
);
INSERT INTO #Customers
VALUES ( 1, 'Kevin', 'Smith', 'M', 1, 2 ) ,
( 2, 'Kevin', 'Smith', 'M', 1, 3 ) ,
( 3, 'Kevin', 'Smith', 'M', 1, 4 ) ,
( 4, 'Kevin', 'Smith', 'O', 0, NULL ) ,
( 5, 'Mary', 'Jones', 'O', 0, NULL ) ,
( 6, 'Wyatt', 'Earp', 'M', 1, 7 ) ,
( 7, 'Wyatt', 'Earp', 'O', 1, NULL ) ,
( 8, 'Bruce', 'Wayn', 'M', 1, 10 ) ,
( 9, 'Brice', 'Wayne', 'M', 1, 10 ) ,
( 10, 'Bruce', 'Wane', 'M', 1, 11 ) ,
( 11, 'Bruce', 'Wayne', 'O', 1, NULL );
SELECT *
FROM #Customers;
DROP TABLE #Customers;
