我的桌子:
1. Hotel - city, hotelNo[pk]
2. Room - roomNo[pk], type, hotelNo[fk]
3. Booking - roomNo[fk], hotelNo[fk],date
我想展示伦敦每家酒店最常预订的房型(hotel.city =' London')
我从互联网上找到的代码都是这样的
SELECT hotelno, type, MAX(y)
FROM
(SELECT hotelno, type, COUNT(type) AS y
FROM booking b, hotel h, room r
WHERE r.roomno = b.roomno AND
r.hotelno = b.hotelno AND
b.hotelno = h.hotelno AND
city = 'London'
GROUP BY hotelno, type)
GROUP BY hotelno, type;
返回三列hotelno,type和max(y)。以及每个酒店的每种类型的预订时间。我只想为每家酒店获得最多预订类型。我怎样才能做到这一点?谢谢你回答。
答案 0 :(得分:1)
我已经重写了我的答案,以解决所有问题。这是查询:
SELECT hotelno, type
FROM
(SELECT hotelno, type, COUNT(type) AS y
FROM booking b, hotel h, room r
WHERE r.roomno = b.roomno AND
r.hotelno = b.hotelno AND
b.hotelno = h.hotelno AND
city = 'London'
GROUP BY hotelno, type) t
where not exists
(SELECT 1
FROM booking b2, hotel h2, room r2
WHERE r2.roomno = b2.roomno AND
r2.hotelno = b2.hotelno AND
b2.hotelno = h2.hotelno AND
h2.city = 'London'
GROUP BY b2.hotelno, r2.type
having b2.hotelno = t.hotelno and count(*) > y);
基本上我在from中的位置进行相同的分组。