I have a table containing information on customers and products in an Access database:
custID product price
--------------------
1 objectA 12,5
1 objectB 54,51
1 objectC 14,85
2 objectE 188,84
2 objectC 14,85
2 objectD 188,84
From that table I would like to get the most expensive product a customer bought by SQL. I tried this:
SELECT a.custID, a.product, max(a.price)
FROM orders AS a INNER JOIN orders AS b ON (a.custID=b.custID) AND (a.price<=b.price)
GROUP BY a.product, a.custID
HAVING count(*)<2;
The result is
1 objectB 54,51
It works all right for all cases where the maximum price occurs only once, but fails when two products have the same (maximum) price. How to make sure to get a result for each customer? (I don’t care wether it will by objectD or objectE for customer 2).
Just a side note:
If you have a more advanced SQL server that supports windowing functions, like SQL Server 2008 you can instead write