2017-02-22 107 views
0

这里我表结构:返回从表中的排序与MySQL

___Rooms:

|--------|------------| 
| ROO_Id | ROO_Name | 
|--------|------------| 
| 1  | Room 1  | 
| 2  | Room 2  | 
| 3  | Room 3  | 
|--------|------------| 

___Bookings:

|--------|------------| 
| BOO_Id | BOO_RoomId | 
|--------|------------| 
| 1  | 1   | 
| 2  | 2   | 
| 3  | 2   | 
|--------|------------| 

___BillableDatas:

|--------|---------------|------------|------------| 
| BIL_Id | BIL_BookingId | BIL_Date | BIL_Item | 
|--------|---------------|------------|------------| 
| 1  | 1    | 2017-02-21 | Night  | 
| 2  | 1    | 2017-02-22 | Night  | 
| 3  | 1    | 2017-02-23 | Night  | 
| 4  | 1    | 2017-02-24 | Night  | 
| 5  | 2    | 2017-02-30 | Night  | 
| 6  | 2    | 2017-02-31 | Night  | 
| 7  | 1    | 2017-02-31 | Night  | 
|--------|---------------|------------|------------| 

我想知道最受欢迎的房间。

期望的结果应该是:

|------------|------------|------------| 
| ROO_Name | Night Nb | Percentage | 
|------------|------------|------------| 
| Room 1  | 5   | 71.42  | 
| Room 2  | 2   | 28.57  | 
| Room 3  | 0   | 0   | 
|------------|------------|------------| 

我已经尝试过:

SELECT r.ROO_Id 
    , 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 = :hotel_id 
GROUP BY r.ROO_Id 
ORDER BY NumBookings DESC 

但它实际上并没有正常工作。

有谁能帮我解决这个问题吗?

您可以使用SQL小提琴: http://sqlfiddle.com/#!9/390b1

非常感谢。

+0

的可能的复制[如何获得一个行的MySQL查询的排名(http://stackoverflow.com/questions/26928755/how-to-得到一个行中的mysql-query) – miken32

+0

仍在挣扎吗?见http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query – Strawberry

+0

@Strawberry,感谢您的工具:http://sqlfiddle.com/#!9/fe0a77 –

回答

0

试试这个

select Roo_Name,coalesce(bookid,0) as nightdb,coalesce(bookid * 10/Boo_Id,0) as percentage 
from ___Rooms r1 
left join 
(select count(BOO_RoomId) as book, BOO_Id 
from ___Bookings group by BOO_Id) b1 
on r1.Roo_Id = b1.Boo_id 
left join 
(select count(Bil_BookingId) as bookid,BIL_BookingId 
from ___BillableDatas 
group by BIL_BookingId) b2 
on b2.BIL_BookingId = b1.BOO_Id group by r1.Roo_Name; 

DEMO

+0

何哇,除了百分比值女巫是完美的,而不是像50这样的东西。请你帮我一下吗? –

+0

好吧我updated.you需要在该格式的形式比计算10 * – denny