I have a schema that looks like this:
Tables
table_id
seat_count
Orders
order_id
table_id
meal_id
Meals
meal_id
price
I am trying to get Tables that have the biggest income per seat_count, i.e.
|idTable| |income| |seat_count|
2 50$ 5
3 60$ 4
4 40$ 3
10 80$ 2
The closest I got was with this query:
SELECT tables.table_id,
SUM(income),
tables.seat_count
FROM (SELECT tables.table_id,
tables.seat_count,
COUNT(orders.meal_id) * meals.price AS income
FROM meals
INNER JOIN (tables
INNER JOIN orders
ON tables.table_id = orders.table_id)
ON meals.meal_id = orders.meal_id
GROUP BY tables.table_id,
tables.seat_count,
meals.price
ORDER BY COUNT(orders.meal_id) * meals.price DESC)
GROUP BY tables.table_id,
tables.seat_count
ORDER BY SUM(income) DESC
But I am stuck, it returns records such as:
table_id, income, seat_count
1 40$ 5
2 30$ 5
4 20$ 4
(I.e with duplicate seat_counts) and I have no idea how to get rid of it.
I think this will give you what you want, though if two tables have the same seat count and income level, it will show both. I tried it on a mockup of your table structure above in Access 2003 (which is why it has the strange join syntax with the brackets).