Wilest
Wilest

Reputation: 1860

T SQL select last sale of each customer

I'm trying to retrieve the last sale date for each customer as follows but it is just returning the last entry in the table:

Select top 1 InvoiceDate
,Customer
from salestable a
order by InvoiceDate desc

Help will be greatly appreciated.

Upvotes: 0

Views: 2831

Answers (1)

Darren
Darren

Reputation: 70718

Don't use TOP 1 - that's why you're returning only 1 result.

Try using MAX and GroupBy Customer

SELECT Customer, MAX(InvoiceDate)
FROM SalesTable
GROUP By Customer
ORDER By MAX(InvoiceDate) DESC

Upvotes: 1

Related Questions