I have three tables:
Shop_Table
shop_id
shop_name
Sells_Table
shop_id
item_id
price
Item_Table
item_id
item_name
The Sells_Table
links the item and shop tables via FK's to their ids. I am trying to get the most expensive item from each store, i.e., output of the form:
(shop_name, item_name, price)
(shop_name, item_name, price)
(shop_name, item_name, price)
(shop_name, item_name, price)
...
where price is the max price item for each shop. I can seem to achieve (shop_name, max(price)) but when I try to include the item_name I am getting multiple entries for the shop_name. My current method is
create view shop_sells_item as
select s.shop_name as shop, i.item_name as item, price
from Shop_Table s
join Sells_Table on (s.shop_id = Sells_Table.shop_id)
join Item_Table i on (i.item_id = Sells_Table.item_id);
select shop, item, max(price)
from shop_sells_item
group by shop;
However, I get an error saying that item must appear in the GROUP BY clause or be used in an aggregate function
, but if I include it then I don't get the max price for each shop, instead I get the max price for each shop,item pair which is of no use.
Also, is using a view the best way? could it be done via a single query?