"hharry" <pa*********@nyc.com> wrote in message
news:11*********************@l41g2000cwc.googlegro ups.com...
Hello All,
I have an issue with dupliate Contact data. Here it is:
I have a Contacts table;
CREATE TABLE CONTACTS
(
SSN int,
fname varchar(40),
lname varchar(40),
address varchar(40),
city varchar(40),
state varchar(2),
zip int
)
Here is some sample data:
SSN: 1112223333
FNAME: FRANK
LNAME: WHALEY
ADDRESS: NULL
CITY: NULL
STATE NY
ZIP 10033
SSN: 1112223333
FNAME: NULL
LNAME: WHALEY
ADDRESS: 100 MADISON AVE
CITY: NEW YORK
STATE NY
ZIP NULL
How do I merge the 2 rows to create one row as follows:
via SQL or T-SQL
SSN: 1112223333
FNAME: FRANK
LNAME: WHALEY
ADDRESS: 100 MADISON AVE
CITY: NEW YORK
STATE NY
ZIP 10033
Pointers appreciated.
Thanks
Based on your sample data, your table has no primary key, or it would not be
possible to have multiple rows with a single SSN. I strongly suggest you add
a primary key to correct your data model and prevent these duplicates,
otherwise you will continue to get bad data in your table. As a quick fix,
you may be able to do something like this:
update dbo.Contacts
set fname = coalesce(c1.fname, c2.fname),
lname = coalesce(c1.lname, c2.lname),
address = coalesce(c1.address, c2.address)
/* etc */
from dbo.Contacts c1
join dbo.Contacts c2
on c1.SSN = c2.SSN
But this assumes that you have only two rows (maximum) per SSN, and there
are no cases where there are different fname or lname values for each SSN,
only one with a NULL and one without. What do you do if one row has fname
'Steven' and another one has fname 'Stephen' with the same SSN? There is no
way to decide automatically which is correct - you have to find out from
some other source.
Simon