LeetCode 262. Trips and Users

Trips 表中存全部出 租 車的行程信息。每段行程有惟一健 Id,Client_Id 和 Driver_Id 是 Users 表中 Users_Id 的外鍵。Status 是枚舉類型,枚舉成員爲 (‘completed’, ‘cancelled_by_driver’, ‘cancelled_by_client’)。sql

+----+-----------+-----------+---------+--------------------+----------+
| Id | Client_Id | Driver_Id | City_Id |        Status      |Request_at|
+----+-----------+-----------+---------+--------------------+----------+
| 1  |     1     |    10     |    1    |     completed      |2013-10-01|
| 2  |     2     |    11     |    1    | cancelled_by_driver|2013-10-01|
| 3  |     3     |    12     |    6    |     completed      |2013-10-01|
| 4  |     4     |    13     |    6    | cancelled_by_client|2013-10-01|
| 5  |     1     |    10     |    1    |     completed      |2013-10-02|
| 6  |     2     |    11     |    6    |     completed      |2013-10-02|
| 7  |     3     |    12     |    6    |     completed      |2013-10-02|
| 8  |     2     |    12     |    12   |     completed      |2013-10-03|
| 9  |     3     |    10     |    12   |     completed      |2013-10-03| 
| 10 |     4     |    13     |    12   | cancelled_by_driver|2013-10-03|
+----+-----------+-----------+---------+--------------------+----------+

Users 表存全部用戶。每一個用戶有惟一鍵 Users_Id。Banned 表示這個用戶是否被禁止,Role 則是一個表示(‘client’, ‘driver’, ‘partner’)的枚舉類型。code

+----------+--------+--------+
| Users_Id | Banned |  Role  |
+----------+--------+--------+
|    1     |   No   | client |
|    2     |   Yes  | client |
|    3     |   No   | client |
|    4     |   No   | client |
|    10    |   No   | driver |
|    11    |   No   | driver |
|    12    |   No   | driver |
|    13    |   No   | driver |
+----------+--------+--------+

寫一段 SQL 語句查出 2013年10月1日 至 2013年10月3日 期間非禁止用戶的取消率。基於上表,你的 SQL 語句應返回以下結果,取消率(Cancellation Rate)保留兩位小數。ip

+------------+-------------------+
|     Day    | Cancellation Rate |
+------------+-------------------+
| 2013-10-01 |       0.33        |
| 2013-10-02 |       0.00        |
| 2013-10-03 |       0.50        |
+------------+-------------------+

解答:it

查詢時建立兩個Trips和Users聚合的臨時表io

計算取消率須要用round(*,2)四捨五入,truncate會報錯class

分組條件統計使用count(),count(case when c=1 then 1 end)cli

# Write your MySQL query statement below
select distinct u.Request_at as Day,round(count(case when (Status= 'cancelled_by_driver' or Status='cancelled_by_client') then 1 end)*1.00/count(1)*1.00,2) as `Cancellation Rate` 
from(
select distinct  Id,Client_Id,Driver_Id, City_Id,Status,Request_at,CID,CB,CR, Users_Id as DID,Banned as DB,Role as DR from 
(select Id,Client_Id,Driver_Id, City_Id,Status,Request_at,Users_Id as CID,Banned as CB,Role as CR from Trips left join Users on Trips.Client_Id=Users_Id)t
 left join Users on t.Driver_Id=Users_Id)u where CB='No' and DB='No' and u.Request_at>='2013-10-01' and u.Request_at<='2013-10-03' group by Day  ;
相關文章
相關標籤/搜索