这是我的表定义:
表___房间:
|--------|-----------|--------|----------|
|ROO_Id |ROO_HotelId|ROO_Name|ROO_Number|
|--------|-----------|--------|----------|
| 1|AAA00 |Room 12 | 12|
| 2|AAA00 |Room 14 | 14|
| 3|AAA00 |Room 16 | 16|
| 4|ZZZ99 |Room 11 | 11|
| 5|ZZZ99 |Room 22 | 22|
| 6|ZZZ99 |Room 33 | 33|
|--------|-----------|--------|----------|
表___预订:
|--------|-----------|----------|
|BOO_Id |BOO_HotelId|BOO_RoomId|
|--------|-----------|----------|
| 1|AAA00 | 1|
| 2|AAA00 | 1|
| 3|AAA00 | 3|
| 4|ZZZ99 | 5|
| 5|ZZZ99 | 5|
| 6|ZZZ99 | 5|
|--------|-----------|----------|
实际上,我有:
AAA00
= 3
AAA00
= 3
我想仅列出属性AAA00
的房间,并按照预订数量最受欢迎的方式对它们进行排名。
所以我使用这个查询:
SELECT r.ROO_Number BOO_RoomId,
( ( ifnull(cnt_book,0)*100)/(SELECT count(*) FROM ___Bookings)) percentage,
ifnull(cnt_book,0) `count`
FROM ___Rooms r
LEFT JOIN (
SELECT BOO_RoomId, count(*) cnt_book
FROM ___Bookings
WHERE BOO_HotelId='AAA00'
GROUP BY BOO_RoomId
) cnt ON r.ROO_Id=cnt.BOO_RoomId
ORDER BY percentage DESC
此查询的预期结果是:
但它让我回到了所有的房间。
你能帮帮我吗?
感谢。
答案 0 :(得分:1)
将CASE
与SUM
一起使用,将每个房间的所有预订加在一起。然后,JOIN
到子查询,以使酒店的每一行都可以预订。
SELECT r.ROO_Name
, Sum(CASE WHEN BOO_id IS NULL THEN 0 ELSE 1 END) NumBookings
, Concat(
Format(
Sum(CASE WHEN BOO_id IS NULL THEN 0 ELSE 1 END)
/ TotalBookings
* 100
, 0)
, '%') AS PercentageTotal
FROM ( __Rooms r LEFT JOIN __Bookings b ON r.ROO_Id = b.BOO_RoomId
) INNER JOIN (SELECT BOO_HotelId
, Count(*) AS TotalBookings
FROM __Bookings
GROUP BY BOO_HotelId
) AS TotalHotelBookings
ON r.ROO_HotelId = TotalHotelBookings.BOO_HotelId
WHERE r.ROO_HotelId = 'AAA00'
GROUP BY r.ROO_Name
ORDER BY r.ROO_Name
;
ROO_Name NumBookings PercentageTotal
-------- ----------- ---------------
Room 12 2 67%
Room 14 0 0%
Room 16 1 33%
Sum(CASE WHEN BOO_id IS NULL THEN 0 ELSE 1 END)
答案 1 :(得分:0)
几乎应该是这样的:
SELECT
foo.ROO_Id,
foo.ROO_Name,
foo.cnt,
(foo.cnt * 100.0) / (SELECT count(*) FROM ___Bookings WHERE BOO_HotelId = foo.ROO_HotelId) AS percentage
FROM (
SELECT
ROO_Id,
ROO_Name,
ROO_HotelId,
(SELECT count(*) FROM ___Bookings b WHERE b.BOO_RoomId = r.ROO_Id) AS cnt
FROM ___Rooms r
WHERE ROO_HotelId = 'AAA00'
) AS foo
ORDER BY cnt DESC