This is an actual requirement that I got from a customer today, so I'm challenging you to see if you can figure out how to code it in SQL.
Leave a comment if you have something that will work better, or is more elegant.
declare
@
Order
table
(RowID
int
identity,Invoice
varchar
(20), CustomerID
varchar
(20), CustomerEmail
varchar
(100), DocAmount
numeric
(19,2) )
insert
into
@
Order
(Invoice, CustomerID, CustomerEmail, DocAmount)
values
(
'INV00100'
,
'001'
,
'Joe@Acompany.com'
,100)
insert
into
@
Order
(Invoice, CustomerID, CustomerEmail, DocAmount)
values
(
'INV00101'
,
'002'
,
'Sam@Bcompany.com'
,110)
insert
into
@
Order
(Invoice, CustomerID, CustomerEmail, DocAmount)
values
(
'INV00102'
,
'003'
,
'Bob@Ccompany.com'
,120)
insert
into
@
Order
(Invoice, CustomerID, CustomerEmail, DocAmount)
values
(
'INV00103'
,
'004'
,
'Tom@Dcompany.com'
,130)
insert
into
@
Order
(Invoice, CustomerID, CustomerEmail, DocAmount)
values
(
'INV00104'
,
'005'
,
'Flo@Fcompany.com'
,140)
insert
into
@
Order
(Invoice, CustomerID, CustomerEmail, DocAmount)
values
(
'INV00105'
,
'006'
,
'Tim@Gcompany.com'
,150)
insert
into
@
Order
(Invoice, CustomerID, CustomerEmail, DocAmount)
values
(
'INV00106'
,
'006'
,
'Tim2@Gcompany.com'
,160)
insert
into
@
Order
(Invoice, CustomerID, CustomerEmail, DocAmount)
values
(
'INV00107'
,
'008'
,
'Sal@Hcompany.com'
,170)
insert
into
@
Order
(Invoice, CustomerID, CustomerEmail, DocAmount)
values
(
'INV00108'
,
'008'
,
'Sal2@Hcompany.com'
,180)
insert
into
@
Order
(Invoice, CustomerID, CustomerEmail, DocAmount)
values
(
'INV00109'
,
'008'
,
'Sal3@Hcompany.com'
,190)
select
*
from
@
Order
This will give us an ORDER table that looks like the below. 10 lines, from 8 companies. The requirement is this:
Use the order table to update the email address field in the customer table. If the same customer has two email address, the newest one should be the main email address, the second oldest one should be the CC, and discard any older email addresses.