MySQL查询以查找每个组中最重复的项目

时间:2017-03-28 18:51:50

标签: mysql phpmyadmin

架构是

Hotel      (hotelNo, hotelName, city) 
Room      (roomNo, hotelNo, rtype, price) 
Booking (hotelNo, guestNo, dateFrom, dateTo, roomNo) 
Guest      (guestNo, guestName, guestAddress) 

我想为布鲁金斯的每家酒店编写最常用房型的SQL查询?(布鲁金斯是一个城市)

我尝试了很多方法,但似乎没有任何方法

select rtype
from room r natural
join hotel h
where rtype = (
        select distinct (rtype)
        from room r1 natural
        join booking
        where r1.hotelno = h.hotelno
        group by rtype
        having count(*) = (
                select max(c)
                from (
                    select count() as c
                    from room r2 natural
                    join booking
                    where r2.hotelno = h.hotelno
                    group by rtype
                    ) as x
                )
        )
group by h,
    hotelno

1 个答案:

答案 0 :(得分:0)

我认为这就是你想要的:

select *
from Room r
join hotel h on r.hotelNo = h.hotelNo
where r.rtype in (
        select r.rtype
        from Room r2
        join Booking b on r2.hotelNo = b.hotelNo
            and r2.roomNo = b.roomNo
        where r.hotelNo = r2.hotelNo
        group by r.rtype
        order by count(*) desc limit 1
        );