简体   繁体   中英

Query to obtain the lowest price per room per hotel in a relational database

I have a relational database model based on a hotel booking site set up for a uni project, however I am stumped by one query.

This is as far as I have gotten:

SELECT DISTINCT
    property.property_id,
    property_name,
    property_description,
    star_rating,
    room_base_price
FROM
    property
INNER JOIN rooms ON property.property_id = rooms.property_id;

The problem is that I have several rooms per property listed in my database. In this query, I want to select the room with the minimum price per hotel. The way I am currently doing it, it is showing every single property with every single room and its individual price.

Can anyone advise me on how I can write a query where I will be able to return the lowest price of a room in a property(ie a hotel), where it will only be one row per hotel instead of returning multiple rows for each property?

Try following query:

SELECT DISTINCT
    property.property_id,
    property_name,
    property_description,
    star_rating,
    room_base_price
FROM
    property
INNER JOIN rooms ON property.property_id = rooms.property_id;
where (rooms.property_id,rooms.room_base_price) in
                                                  (select property_id,min(room_base_price) 
                                                   from rooms
                                                   group by property_id
                                                  )
;

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM