将Sql请求分成2个表来获取每行的百分比

时间:2014-04-18 13:20:15

标签: php mysql sql

我有两个这样的SQL表:

___房间:

ROO_Id    ROO_Number
1         101
2         201

___预订:

BOO_Id    BOO_RoomNumber
1         1   
2         1
3         2

我想要回复一张桌子,上面有我所有的房间,每个房间的百分比。

BOO_RoomNumber percentage count
101            66%         2 
201            33%         1

感谢。

2 个答案:

答案 0 :(得分:0)

尝试使用它:

SELECT r.id as BOO_RoomNumber, ((booked/(select count(id) from BOOKINGS))*100) as percentage, booked as `count`
FROM ROOMS as r
LEFT JOIN 
(
SELECT count(id) as booked, roomId
FROM BOOKINGS
GROUP BY roomId
) as b on b.roomId=r.id

答案 1 :(得分:0)

以下是答案:

<强>已更新

select r.ROO_Number BOO_RoomNumber, ((ifnull(cnt_book,0)*100)/(select count(*) from Bookings)) percentage, ifnull(cnt_book,0) `count`
from Rooms r left join (select BOO_RoomNumber, count(*) cnt_book
           from Bookings
           group by BOO_RoomNumber) cnt on r.ROO_Id=cnt.BOO_RoomNumber

工作SQLFiddle