Question

Hi I have a table called items which looks as follow:

items table

itemname | itemprice
---------------------
orange   | 0.50
pear     | 0.40
apple    | 0.40
banana   | 0.75

I also have a table that records each sale:

sales table

date     | itemname | qty
---------------------
17/12/13 | orange   | 4
22/12/13 | banana   | 6
23/12/13 | banana   | 2
29/12/13 | pear     | 3
02/01/14 | orange   | 2
05/01/14 | pear     | 6
05/01/14 | banana   | 5
06/01/14 | apple    | 2

What I want to do is get the itemname and price of the 2 most sold items. So the query should return:

itemname | itemprice
---------------------
banana   | 0.70
pear     | 0.40

I can get the 2 most common items but that is wrong as the qty needs to be taken into account and not the frequency of the itemname in the sales table.

Was it helpful?

Solution

SELECT i.itemname, i.itemprice
FROM items i
JOIN sales s ON i.itemname = s.itemname
GROUP BY s.itemname
ORDER BY SUM(s.qty) DESC
LIMIT 2

SQL Fiddle

If you want to be ANSI-compliant, change the GROUP BY to

GROUP BY i.itemname, i.itemprice
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top