2017-02-22 40 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