stevegray
4Penny.net
Points: 55409

3/8/2019 11:27:38 AM

SQL Puzzler 3/8/2019

* This article, and all our great SQL (General) documentation, Is available on the SQL (General) menu

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. 

Give it a careful though before you read my answer. 

Leave a comment if you have something that will work better, or is more elegant.

So, we start with this:

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. 

The final result should look like the second screen shot. 

How would you code that?

 

 

4Penny.net
Version: All
Section: SQL Scripts
Table Definition Quick Links
All Tables
SOP Tables
RM Tables
GL Tables
POP Tables
HR Tables
PM Tables
UPR Tables
IV Tables
Olympic Tables
3