思维斩获:计算xxx率范式
Trips 表中存所有出租车的行程信息。
每段行程有唯一键 Id,Client_Id 和 Driver_Id 是 Users 表中 Users_Id 的外键。Status 是枚举类型,枚举成员为 (‘completed’, ‘cancelled_by_driver’, ‘cancelled_by_client’)。
Users 表存所有用户。每个用户有唯一键 Users_Id。Banned 表示这个用户是否被禁止,Role 则是一个表示(‘client’, ‘driver’, ‘partner’)的枚举类型。
取消率的计算方式:(被司机或乘客取消的非禁止用户生成的订单数量) / (非禁止用户生成的订单总数);
-- 进入建好的数据库
use data_2021q1_tiku;
-- 建表
create table `trips` (
`id` int default null,
`client_id` int default null,
`driver_id` int default null,
`city_id` int default null,
`status` varchar(32) default null,
`request_at` date default null
) engine=innodb default charset=utf8mb4;
insert into `trips` values (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');
drop table trips;
create table `users` (
`users_id` int default null,
`banned` varchar(32) default null,
`role` varchar(32) default null
) engine=innodb default charset=utf8mb4;
insert into `users` values (1,'no','client'),
(2,'yes','client'),
(3,'no','client'),
(4,'no','client'),
(10,'no','driver'),
(11,'no','driver'),
(12,'no','driver'),
(13,'no','driver');
--
select * from trips;
select * from users;
/* 写一段 SQL 语句查出 2013年10月1日 至 2013年10月3日 期间非禁止用户的取消率。 取消率的计算方式:(被司机或乘客取消的非禁止用户生成的订单数量) / (非禁止用户生成的订单总数); */
-- 需求业务理解:输出两个字段:日期,取消率
select request_at as day
,count(1)
,sum(case when trips.status = 'cancelled_by_driver' then 1
when trips.status = 'cancelled_by_client' then 1
else 0 end) as 被取消的订单
,cast(sum(case
when trips.status = 'cancelled_by_driver' then 1
when trips.status = 'cancelled_by_client' then 1
else 0 end) / count(1) as decimal(5,2)) as Cancellation_Rate
from trips
inner join users as uc on trips.client_id = uc.users_id and uc.banned = 'no'
inner join users as ud on trips.driver_id = ud.users_id and ud.banned = 'no'
group by request_at;
统计xxx率 ~
更多请持续关注……
问题:是因为枚举的原因,所以表之间才如此关联么……?
本文地址:https://blog.csdn.net/weixin_44976611/article/details/112633955