话不多说, 先看数据表信息.
trips 表中存所有出租车的行程信息。每段行程有唯一键 id,client_id 和 driver_id 是 users 表中 users_id 的外键。status 是枚举类型,枚举成员为 (‘completed’, ‘cancelled_by_driver’, ‘cancelled_by_client’)。
| id | client_id | driver_id | city_id | status | request_at |
|----|-----------|-----------|---------|--------------------|--------------|
| 1 | 1 | 10 | 1 | completed | 2013-10-1 |
| 2 | 2 | 11 | 1 | cancelled_by_driver| 2013-10-1 |
| 3 | 3 | 12 | 6 | completed | 2013-10-1 |
| 4 | 4 | 13 | 6 | cancelled_by_client| 2013-10-1 |
| 5 | 1 | 10 | 1 | completed | 2013-10-2 |
| 6 | 2 | 11 | 6 | completed | 2013-10-2 |
| 7 | 3 | 12 | 6 | completed | 2013-10-2 |
| 8 | 2 | 12 | 12 | completed | 2013-10-3 |
| 9 | 3 | 10 | 12 | completed | 2013-10-3 |
| 10 | 4 | 13 | 12 | cancelled_by_driver| 2013-10-3 |
users 表存所有用户。每个用户有唯一键 users_id。banned 表示这个用户是否被禁止,role 则是一个表示(‘client’, ‘driver’, ‘partner’)的枚举类型。
+----------+--------+--------+
| 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)保留两位小数。
话不多说, 进行拆解~
select
t.request_at as `date`,
round(count(case when t.status like 'cancelled%' then 1 end) / count(*), 2) as `cancellation rate`
from
trips t
join
users u on t.client_id = u.users_id
where
u.banned = 'no'
and t.request_at between '2013-10-01' and '2013-10-03'
group by
t.request_at;
最后给大家介绍一下我这边的创建数据表和插入数据的操作步骤, 想要自己测试的话, 可以参考:
-- 创建 users 表
CREATE TABLE users (
users_id INT PRIMARY KEY,
banned VARCHAR(3),
role VARCHAR(10)
);
-- 插入 users 数据
INSERT INTO users (users_id, banned, role)
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');
-- 创建 trips 表
CREATE TABLE trips (
id INT PRIMARY KEY,
client_id INT,
driver_id INT,
city_id INT,
status VARCHAR(20),
request_at DATE,
FOREIGN KEY (client_id) REFERENCES users(users_id),
FOREIGN KEY (driver_id) REFERENCES users(users_id)
);
-- 插入 trips 数据
INSERT INTO trips (id, client_id, driver_id, city_id, status, request_at)
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');