Solved

# Transact SQL Combine Customer Records

Posted on 2011-09-20
245 Views

Occasionally I get duplicate customer records because they have setup a second account with their work email and forgot that they had originally setup their account with their home email.

I want to write a query that will essentially combine the 2 records and then delete 1 of them.

So, for example, I want to take record id #202 and record id #561 and combine 3 fields: TotalSpent, TotalNumberof Orders, and logincount and write the totals into record id #561. Then, upon successful update, delete record id #202.

Any help will be appreciated.

David
0
Question by:DLockwood
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2

LVL 32

Expert Comment

ID: 36571018
try this
;with
cte1 as
(
select AccountNum, Email, Spent, Orders, logincount,
ROW_NUMBER() over (PARTITION by AccountNum order by ID desc) RN
from customer
),
cte2 as
(
select AccountNum, SUM(Spent) TotalSpent, SUM(Orders) TotalOrders, sum(logincount) logincount, max(Email) Email, COUNT(*) Num
from customer
group by AccountNum
)

update cte1
set Spent = B.TotalSpent,
Email = coalesce(Email, B.Email),
Orders = B.TotalOrders,
from cte2 B
inner join cte1 on cte1.AccountNum = B.AccountNum and B.Num > 1
where RN = 1

delete
from cte1
where rn > 1
0

Accepted Solution

DLockwood earned 0 total points
ID: 36580460
I found the easy answer to this question somewhere else.

The easy answer is to set 4 local variables equal to the values in the table that I want to delete.

Then run a simple update query updating the values to the old value + the local variable. Then delete the old record.

0

Author Closing Comment

ID: 36708074
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In SQL Server, when rows are selected from a table, does it retrieve data in the order in which it is inserted?  Many believe this is the case. Let us try to examine for ourselves with an example. To get started, use the following script, wh…
Data architecture is an important aspect in Software as a Service (SaaS) delivery model. This article is a study on the database of a single-tenant application that could be extended to support multiple tenants. The application is web-based develope…
Simple Linear Regression
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…
###### Suggested Courses
Course of the Month2 days, left to enroll