Sql query to get the tables of the restaurants that have the most revenue on seat_count

I have a circuit 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 the Tables that have the most revenue on seat_count, i.e.

 |idTable| |income| |seat_count|
     2        50$        5
     3        60$        4
     4        40$        3
     10       80$        2

The closest I got with this request:

 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'm stuck, it returns records, such as:

 table_id, income, seat_count
   1         40$     5
   2         30$     5
   4         20$     4

(Ie with duplicate seat_counts) and I have no idea how to get rid of it.

+3
source share
1 answer

I think this will give you what you want, although if the two tables have the same number of seats and income level, it will show both. I tried this on the layout of your table structure above in Access 2003 (which is why it has a strange syntax for joining brackets).

select sub1.table_id, sub1.seat_count, sub1.income
from
(
    SELECT Tables.table_id, Tables.seat_count, Sum(Meals.price) AS Income
    FROM (Tables INNER JOIN Orders ON Tables.table_id = Orders.table_id) INNER JOIN Meals ON Orders.meal_id = Meals.meal_id
    GROUP BY Tables.table_id, Tables.seat_count
) sub1
inner join 
(
    select seat_count, max(Income) as Maxincome
    from
    (
        SELECT Tables.table_id, Tables.seat_count, Sum(Meals.price) AS Income
        FROM (Tables INNER JOIN Orders ON Tables.table_id = Orders.table_id) INNER JOIN Meals ON Orders.meal_id = Meals.meal_id
        GROUP BY Tables.table_id, Tables.seat_count
    ) sub
    group by seat_count
) sub2 on (sub1.seat_count = sub2.seat_count and sub1.income = sub2.maxincome);
+2
source

All Articles