November 1, 2010 at 3:30 pm
I have billing customers which has multiple shipping addresses. Unfortunately, we did a poor job of data governance and so we have the same shipping address repeated multiple times. For example, we have instance where a customer has 20+ shipping address records for the same shipping zip code.
I would like to get one customer record per address per zip code. I have created a table which has all the customers with all the multiple shipping addresses and also with the last time an order was shipped to that shipping address.
I would like to create a query where I can only get one record per zip code per customer and that record needs to be the latest order date.
Can someone give my some insight? Thanks
November 1, 2010 at 3:39 pm
select top 1 ... order by order_date desc
Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes
November 1, 2010 at 3:46 pm
... or you could use a subquery to return the ID per per zip code per customer with max(order date).
Use this subquery to join back to your original table.
November 1, 2010 at 3:58 pm
Or a CTE like below:
;WITH CUSTADDR
AS
(
SELECT
CUSTOMER_ID,
ZIPCODE,
ADDR,
ROW_NUMBER() OVER(PARTITION BY CUSTOMER_ID, ZIPCODE ORDER BY SHIPPING_DATE DESC) AS RowNr
FROM CUSTOMERADDRESS -- Your table
)
SELECT
CUSTOMER_ID,
ZIPCODE,
ADDR
FROM CUSTADDR
WHERE RowNr = 1
Andreas Goldman
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply