2011-05-02 163 views
1

我有這樣的模式:SQL查詢援助

Hotel (**hotelNo**, hotelName, city) 
Room (**roomNo, hotelNo**, type, price) 
Booking (**hotelNo, guestNo, dateFrom**, dateTo, roomNo) 
Guest (**guestNo**, guestName, guestAddress) 
** denotes primary keys 

我要完成這個查詢:

  • 顯示每家酒店和其最常見的房間。

我有這個疑問,這是不完全正確:

SELECT r.hotelno, type, count(*) 
FROM Hotel h, room r 
WHERE h.hotelNo = r.hotelno 
GROUP BY r.hotelNo, type; 

這就是它輸出:

enter image description here

我在做什麼錯?

回答

1

它看起來好像您正在尋找在每家酒店有最大數量的預訂房間類型的房間類型 - 合計(最大)另一個聚合(房間類型的預訂計數)。

將其分段構建。每種類型的客房預訂的在每個酒店數量:

SELECT r.hotelno, r.type, count(*) AS num_bookings 
    FROM Booking AS b 
    JOIN Room AS r ON b.hotelNo = r.hotelno AND b.roomNo = r.roomNo 
GROUP BY r.hotelNo, r.type; 

現在,你需要知道哪些類型的客房在各酒店最大。這必須分兩個階段完成:

  1. 找到任何類型的酒店的最大預訂數量。
  2. 找到最大號碼的房間類型。

第一階段是:

SELECT s.hotelno, MAX(num_bookings) AS max_bookings 
    FROM (SELECT r.hotelno, r.type, count(*) AS num_bookings 
      FROM Booking AS b 
      JOIN Room AS r ON b.hotelNo = r.hotelno AND b.roomNo = r.roomNo 
     GROUP BY r.hotelNo, r.type 
     ) AS s 
GROUP BY s.hotelno; 

第二階段採用既爲最終答案之前的結果:

SELECT t.hotelno, t.type 
    FROM (SELECT r.hotelno, r.type, count(*) AS num_bookings 
      FROM Booking AS b 
      JOIN Room AS r ON b.hotelNo = r.hotelno AND b.roomNo = r.roomNo 
     GROUP BY r.hotelNo, r.type) AS t 
    JOIN (SELECT s.hotelno, MAX(num_bookings) AS max_bookings 
      FROM (SELECT r.hotelno, r.type, count(*) AS num_bookings 
        FROM Booking AS b 
        JOIN Room AS r ON b.hotelNo = r.hotelno AND b.roomNo = r.roomNo 
       GROUP BY r.hotelNo, r.type 
       ) AS s 
     GROUP BY s.hotelno) AS m 
    ON t.hotelno = m.hotelno AND t.num_bookings = m.max_bookings; 

如果你的DBMS WITH子句支持,你可以寫更多簡潔。

1

如果您正在尋找知名度,您需要考慮預訂表。將預訂表添加到您的FROM語句中,鏈接到hotelNo和roomNo並在預訂表中進行計數。這應該給你你想要的數量。

編輯: 這是給你一些示例代碼(測試):

SELECT TOP (100) PERCENT dbo.Hotel.hotelName, dbo.Room.type, COUNT(*) AS Count 
FROM dbo.Booking INNER JOIN 
dbo.Room ON dbo.Booking.roomNo = dbo.Room.roomNo AND dbo.Booking.hotelNo = dbo.Room.hotelNo 
INNER JOIN dbo.Hotel ON dbo.Room.hotelNo = dbo.Hotel.hotelNo 
GROUP BY dbo.Hotel.hotelName, dbo.Room.type 
ORDER BY Count DESC 
0

我認爲你將不得不使用一個內部查詢得到這一個工作:

SELECT dbo.Hotel.hotelName, pop.type, pop.Count 
FROM dbo.Hotel 
    INNER JOIN (
     SELECT TOP 1 dbo.Hotel.hotelNo, dbo.Room.type, COUNT(*) AS Count 
     FROM dbo.Hotel 
      INNER JOIN dbo.Room ON dbo.Room.hotelNo = dbo.Hotel.hotelNo 
      INNER JOIN dbo.Booking ON dbo.Booking.roomNo = dbo.Room.roomNo AND dbo.Booking.hotelNo = dbo.Hotel.hotelNo 
     GROUP BY dbo.Hotel.hotelNo, dbo.Room.type 
     ORDER BY Count DESC, dbo.Room.type 
    ) AS pop ON pop.hotelNo = dbo.Hotel.HotelNo 
ORDER BY dbo.Hotel.hotelName