1

我正在尝试在一个查询中加入 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

我怎样才能做到这一点 ?

4

5 回答 5

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
于 2012-06-22T16:19:02.987 回答
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 

我不积极,不知道更多关于表格的信息。特别是,预订具有房间和酒店所没有的时间成分。这如何纳入您的查询中?

于 2012-06-22T16:27:42.197 回答
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
于 2012-06-22T16:29:41.693 回答
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
于 2012-06-22T16:34:19.443 回答
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

于 2012-06-22T17:56:53.507 回答