试图获得在查询中获得最大利润的酒店房间

trying to get the rooms of hotels that got the most profit in a query

我正在尝试执行一个查询,该查询会给出每家酒店(25 家酒店)中最赚钱的房间的总和

下面是我的查询:

SELECT hotels.hotel_id,rooms.room_id,hotel_name,room_number,sum(rooms.room_price) AS profit,COUNT(rooms.room_id) AS count FROM hotels,rooms,bookings WHERE hotels.hotel_id=rooms.hotel_id AND rooms.room_id=bookings.room_id GROUP BY rooms.room_id

这是我得到的最接近的结果..忽略酒店名称语言

This is the outcome that I've reached so far,

hotels

rooms

bookings p.1

bookings p.2 (remaining records)

hotel_id1有5个房间,room_number300赚了最多。我只想展示每家酒店的最大利润。其他利润少的房间我不要了


更新: 所以我解决了一个类似的查询,我想在其中获得利润最高的最好的 2 个房间。但是,我只是想不出有什么功能可以给我每家酒店的最大利润。需要一点提示或帮助

请尝试以下一次:

SELECT RO_BOOK.HOTEL_ID,
       RO_BOOK.ROOM_ID,
       RO_BOOK.ROOM_NUMBER,
       RO_BOOK.TOTAL_BOOKINGS,
       MAX(RO_BOOK.TOTAL_EARNINGS) PROFITS
FROM(
    SELECT  ROOMS.HOTEL_ID
        ROOMS.ROOM_ID,
        ROOMS.ROOM_NUMBER,
        COUNT(ROOMS.ROOM_ID) TOTAL_BOOKINGS
        SUM(ROOMS.ROOM_PRICE) TOTAL_EARNINGS
    FROM 
        ROOMS, BOOKINGS
    WHERE 
        BOOKINGS.ROOM_ID = ROOMS.ROOM_ID
        GROUP BY ROOMS.ROOM_ID) RO_BOOK
GROUP BY RO_BOOK.HOTEL_ID ;

它类似于@tcadidot0 代码,但列 MAX(a.tc) AS "Count" return 最大计数,与 ROOM_ID 无关。 例如: 如果酒店 1 有 2 个房间,比如 R100 和 R200。 R100 的成本为 1000,R200 的成本为 100。 R100 预订次数为 1 次,R200 预订次数为 3 次。 所以查询将 return: 酒店 1,R100,计数 2,利润 1000。

如有问题请指正

试试这个查询:

SELECT * FROM 
(SELECT hotels.hotel_id,rooms.room_id,hotel_name,room_number,SUM(rooms.room_price) AS profit,COUNT(rooms.room_id) AS COUNT
FROM hotels,rooms,bookings
WHERE hotels.hotel_id=rooms.hotel_id
AND rooms.room_id=bookings.room_id
GROUP BY rooms.room_id) a GROUP BY hotel_id;

编辑:

这可能会做到:

SELECT hotel_id,room_id,room_number,MAX(a.tc) AS "Count",MAX(tp) AS "MostProfit" FROM
(SELECT hotel_id,rooms.room_id,room_number,COUNT(rooms.room_id) AS "tc",SUM(room_price) AS "tp" FROM rooms JOIN bookings 
ON rooms.room_id=bookings.room_id
GROUP BY rooms.room_id) a GROUP BY hotel_id