Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql query to get restaurant tables that have the biggest income per seat_count

Tags:

sql

ms-access

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.

like image 203
murmu Avatar asked Dec 21 '25 22:12

murmu


1 Answers

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).

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);
like image 170
patmortech Avatar answered Dec 23 '25 17:12

patmortech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!