Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select each customer's most recent purchase

Tags:

sql

ms-access

In Microsoft Access 2010, I want to run a query that lists only the most recent purchase made by each and every customer. Here is the SQL that I have so far:

SELECT ClientNumber, DateOfPurchase  
FROM ordersTable WHERE ClientNumber IN (  
SELECT MAX(DateOfPurchase)  
FROM ordersTable  
GROUP BY ClientNumber  
);  

The problem is that this query is not returning any data, despite their being relevant data in ordersTable. How do I alter the code above so that it works?

like image 206
CodeMed Avatar asked Feb 03 '26 06:02

CodeMed


1 Answers

Typically you can solve this by joining the table to itself:

SELECT o.ClientNumber, o.DateOfPurchase  
FROM ordersTable o JOIN (
    SELECT MAX(DateOfPurchase) as MaxDateOfPurchase, ClientNumber
    FROM ordersTable  
    GROUP BY ClientNumber  
) t ON o.ClientNumber = t.ClientNumber AND o.DateOfPurchase = t.MaxDateOfPurchase

With that said, if you're not selecting any other fields, the subquery will work by itself:

SELECT MAX(DateOfPurchase) as MaxDateOfPurchase, ClientNumber
FROM ordersTable  
GROUP BY ClientNumber  

Edit, given you're using MS Access, you will perhaps need the keyword AS when aliasing a column.

like image 66
sgeddes Avatar answered Feb 04 '26 20:02

sgeddes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!