LeetCode 【困难】数据库-第262:行程和用户

写一段 SQL 语句查出 :
1."2013-10-01" 至 "2013-10-03" 期间
2.非禁止用户(乘客和司机都必须未被禁止)的取消率--( 非禁止用户即 Banned 为 No 的用户,禁止用户即 Banned 为 Yes 的用户 )
( 取消率 的计算方式如下:(被司机或乘客取消的非禁止用户生成的订单数量) / (非禁止用户生成的订单总数) )
返回结果表中的数据可以按任意顺序组织。其中取消率 Cancellation Rate 需要四舍五入保留 两位小数 。

方法一:使用平均数来计算取消率。

select 
request_at as Day,
round(avg(Status!='completed'), 2) as 'Cancellation Rate'
from trips t 
join users u1 on (t.client_id = u1.users_id and u1.banned ='no' )
join users u2 on (t.driver_id = u2.users_id and u2.banned ='no')
where request_at between '2013-10-01' AND '2013-10-03'
group by request_at;

方法二:通过计算---case when

select  
request_at as Day,
round (sum(case when t.Status = 'completed' then 0 else 1 end)/count(t.Status),2) as 'Cancellation Rate' 
from Trips t
join users u1 on (t.client_id = u1.users_id and u1.banned ='no' )
join users u2 on (t.driver_id = u2.users_id and u2.banned ='no')
where request_at between '2013-10-01' AND '2013-10-03'group by request_at;
原文地址:https://www.cnblogs.com/Tdazheng/p/14919378.html