在MySQL中加入2个sql查询

时间:2012-06-22 16:16:01

标签: mysql sql

我正在尝试在一个查询中加入2个SQL查询。

第一个获得每个酒店的房间数。 第二个获得酒店的托运客人数。 我想要获得每家酒店的入住率。

SELECT hotel_id, count(room_id)  
FROM  room  
group by room.hotel_id

SELECT h.hotel_id, count(k.room_id) 
FROM room_reservation as kr , room as k , hotel as h
where kr.room_id = k.room_id and k.hotel_id = h.hotel_id 
group by k.hotel_id

我该怎么做?

5 个答案:

答案 0 :(得分:1)

select aux.hotel_id, ((coalesce(aux2.total, 0)*1.0)/aux.total)*100 as 'ocupancy rate'
from (SELECT hotel_id, count(room_id) as 'total' 
      FROM  room  
      group by room.hotel_id) aux
LEFT OUTER JOIN (SELECT h.hotel_id, COUNT(k.room_id) as 'total'
                 FROM room_reservation as kr
                 INNER JOIN room as k ON (kr.room_id = k.room_id)
                 INNER JOIN hotel as h ON (k.hotel_id = h.hotel_id) 
                 GROUP BY k.hotel_id) aux2 on aux.hotel_id = aux2.hotel_id

答案 1 :(得分:0)

您可以使用一个查询完成此操作。一种方法就是将您的查询结合在一起。

但是,我认为以下内容可以一举做到:

SELECT r.hotel_id, count(distinct k.room_id) as numrooms,
       count(distinct kr.room_id) as numreserved
FROM room k left outer join
     room_reservation kr
     on kr.room_id = k.room_id 
group by r.hotel_id 

在不了解桌子的情况下,我并不积极。特别是,预订有时间部分,房间和酒店没有。如何将其纳入您的查询?

答案 2 :(得分:0)

我希望这是不言自明的:

select hotel_id, sum(guests)/count(room_id) occupancy_level
from (
  select r.hotel_id, r.room_id, count(*) guests
  from room r
  left join room_reservation rr on rr.room_id = r.room_id
  group by r.hotel_id, r.room_id
) temp
group by hotel_id

更新 - 受到@Gordon Linoff的启发,包括未预留的房间

select r.hotel_id, count(*) / count(distinct r.room_id) occupancy_level
from room r
left join room_reservation rr on rr.room_id = r.room_id
group by r.hotel_id, r.room_id

答案 3 :(得分:0)

加入您的所有查询,汇总以获得每间酒店的客房/预订数量,并除以:

SELECT hotel_id, 
    COUNT(DISTINCT r.room_id) / CONVERT(decimal, COUNT(*)) * 100.0 AS occupancy_rate
FROM hotel h
    LEFT OUTER JOIN room r ON h.hotel_id = r.hotel_id
    LEFT OUTER JOIN room_reservation rr ON r.room_id = rr.room_id
GROUP BY h.hotel_id

答案 4 :(得分:0)

可以非常简单地假设在room_reservation表中的任何给定时间总是与总酒店房间相同或更少的预订,并且酒店房间将只有0或1个相应的行room_reservation表因为之前的房间预订已被删除(这似乎是因为在您的第二个查询中,您没有进行任何类型的过滤,例如仅选择每个房间的最近预订等):

SELECT 
    a.hotel_id, 
    (COUNT(b.room_id) / COUNT(*))*100 AS occupancy_rate  
FROM 
    room a
LEFT JOIN
    room_reservation b ON a.room_id = b.room_id
GROUP BY 
    a.hotel_id 

如果您需要更多关于酒店的详细信息,而不仅仅是hotel_id,则需要额外的INNER JOIN