2014-09-30 41 views
1

我試圖創建一個查詢來獲得一個房間有預留的所有MAX計數,我的查詢返回一切正確,但是當我嘗試查找MAX時,它只會返回1個結果,而不是3應該顯示它只會返回最大數量。多個名稱的SQL Server MAX

當前結果:只顯示1家酒店在HAVING COUNT查詢之前的

HotelName      RoomType    Room Count 
------------------------------ -------------------- ----------- 
MGM Grand      Single    6 

結果的MAX:

HotelName      RoomType    Room Count 
------------------------------ -------------------- ----------- 
The Mirage      Double    3 
The Palazzo     Double    1 
MGM Grand      Double Deluxe  4 
MGM Grand      Family    2 
The Mirage      Family    4 
MGM Grand      Single    6 
The Palazzo     Suite    1 

預期結果:注:上宮既然是有兩個是是相同的計數,它顯示兩者或一個或另一個將工作

HotelName      RoomType    Room Count 
------------------------------ -------------------- ----------- 
MGM Grand      Single    6 
The Mirage      Family    4 
The Palazzo     Suite    1 

當前S cript:

SELECT h.HotelName, hr.RoomType, COUNT(*) AS 'Room Count' 
FROM RESERVATIONDETAIL AS rd 
JOIN ROOM r ON r.RoomID = rd.RoomID 
JOIN HOTELROOMTYPE hr ON hr.HotelRoomTypeID = r.HotelRoomTypeID 
JOIN HOTEL h ON h.HotelID = hr.HotelID 
WHERE rd.CheckinDate >= '140901' AND rd.CheckinDate <= '141031' 
GROUP BY h.HotelName, hr.RoomType 
HAVING COUNT(*) = 
(SELECT MAX(RoomCount) 
FROM 
(SELECT h.HotelName, COUNT(*) AS RoomCount 
FROM RESERVATIONDETAIL AS rd 
JOIN ROOM r ON r.RoomID = rd.RoomID 
JOIN HOTELROOMTYPE hr ON hr.HotelRoomTypeID = r.HotelRoomTypeID 
JOIN HOTEL h ON h.HotelID = hr.HotelID 
WHERE rd.CheckinDate >= '140901' AND rd.CheckinDate <= '141031' 
GROUP BY h.HotelName, hr.RoomType)x) 
+0

你需要'MAX(COUNT)...... GROUPBY HotelName'如果MAX(計數)在剛剛記錄您將獲得所有記錄的MAX。通過使用您所在的羣組彙總所有各種酒店名稱。 – JonH 2014-09-30 16:10:35

回答

2

我認爲row_number function應該得到你想要的。有可能是一種方法用一個子查詢少要做到這一點,但我相信一般的想法是:

select d.HotelName, d.RoomType, d.[Room Count] 
from (
    select d.*, row_number() over (partition by HotelName order by [Room Count] desc) rn 
    from (
    SELECT h.HotelName, hr.RoomType, COUNT(*) AS 'Room Count' 
    FROM RESERVATIONDETAIL AS rd 
    JOIN ROOM r ON r.RoomID = rd.RoomID 
    JOIN HOTELROOMTYPE hr ON hr.HotelRoomTypeID = r.HotelRoomTypeID 
    JOIN HOTEL h ON h.HotelID = hr.HotelID 
    WHERE rd.CheckinDate >= '140901' AND rd.CheckinDate <= '141031' 
    GROUP BY h.HotelName, hr.RoomType 
) d 
) d 
where d.rn = 1 
+0

這樣做的竅門,並沒有意識到這一點。謝謝。 – SaSquadge 2014-09-30 16:24:12