Search code examples
sqloracle-databasetop-n

Finding the MAX


Possible Duplicate:
Oracle SQL - How to Retrieve highest 5 values of a column

I have a simple question for someone who knows anything about SQL but since i'm very new and although I have tried many different ways, I can never seem to get the syntax correct. I want to display only the average hotel which is the MAX result. Currently it displays the average of all the hotels individually. Is this something I can use the MAX function for? I am using oracle

SELECT HOTEL.H_NAME "HOTEL NAME", ROUND(AVG (R_PRICE), 1) "AVERAGE ROOM PRICE"
FROM ROOM JOIN HOTEL ON HOTEL.HOTEL_NO = ROOM.HOTEL_NO
WHERE HOTEL.H_NAME = 'Shangra_La'
OR HOTEL.H_NAME = 'Hilton'
OR HOTEL.H_NAME = 'Sheraton'
GROUP BY HOTEL.H_NAME
ORDER BY HOTEL.H_NAME;

Solution

  • In Oracle you can use the ROWNUM pseudo column.

    SELECT * FROM
    (
        SELECT 
            HOTEL.H_NAME "HOTEL NAME", 
            ROUND(AVG (R_PRICE), 1) "AVERAGE ROOM PRICE" 
        FROM
            ROOM 
                JOIN HOTEL ON HOTEL.HOTEL_NO = ROOM.HOTEL_NO 
        WHERE HOTEL.H_NAME IN ('Shangra_La','Hilton','Sheraton')
        GROUP BY HOTEL.H_NAME 
    ) v
    WHERE ROWNUM = 1
    ORDER BY "AVERAGE ROOM PRICE" DESC;