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

时间:2019-03-14 02:48:47

标签: mysql sql heidisql

我正在尝试执行一个查询,该查询为我提供了每家酒店(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_id 1有5个房间,其中房间号300利润最大。我只想显示每家酒店的最大利润。我不需要其他利润较少的房间。


更新: 所以我解决了一个类似的查询,在这里我想获得利润最高的最好的2个房间。但是,我只是想不出任何能给我每家酒店最大收益的功能。很少的提示或帮助会被申请

2 个答案:

答案 0 :(得分:0)

请在下面尝试一次:

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”返回最大计数,而与ROOM_ID无关。 例如:     如果旅馆1有2个房间,例如R100和R200。 R100的成本为1000,R200的成本为100。     R100预订的次数为1,R200的预订次数为3。     因此查询将返回:         HOTEL 1,R100,COUNT 2,利润1000。

如果我回答错了,请纠正我。

答案 1 :(得分:0)

尝试此查询:

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