SQL Sever - Group last paid price by customer and product code

I am trying to write a query that will do the following.

I have a table with seperate sales order lines on it. Each line details the customer, product sold, the price sold at, and the date of the sale.

I am trying to establish for each product code, what the last price we sold it for was for each separate customer.

For example using my input below I would expect Product code ABC to return '10' for Brian, '20' for Gary, and '50 for Sam.

Below is complete set of results I would expect for all product codes.
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Vitor MontalvãoMSSQL Senior EngineerCommented:
You have many ways to do this. Here's one:
WITH CTE_LastCustSaleByProd
AS (
      SELECT Customer, Product, MAX(Date) LastDate
      FROM Sales
      GROUP BY Customer, Product
SELECT s.OrderNo, s.Customer, s.Product, s.Date, s.Price
FROM Sales s
    INNER JOIN CTE_LastCustSaleByProd c ON s.Customer = c.Customer AND s.Product = c.Product AND s.Date = LastDate

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Scott PletcherSenior DBACommented:
SELECT qry1.[Product Code], qry1.Customer, qry1.Price, qry1.Date
    SELECT *, ROW_NUMBER() OVER(PARTITION BY [Product Code], Customer ORDER BY Date DESC) AS row_num
    FROM dbo.table_name
) AS qry1
WHERE row_num = 1
ORDER BY qry1.[Product Code], qry1.Customer
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.