[英]SQL query to find the cancellation rate of requests made between two dates using WITH
我试图了解从两个查询中划分计数和的正确方法。
我正在自学 sql 并在线练习。
问题:
编写一个 SQL 查询以查找 2017-08-01 和 2017-08-03 之间发出的请求的取消率。 取消率是通过将取消的请求数除以每天的总乘车次数得出的。 结果表应该有 2 列,即显示每一天的 Day 和提供当天取消率的 Cancellation Rate。
表是:
我尝试的是:
with
cancelled_rides as
(select count(*) cancel_count, status, Request_id
from TRIPS
where status = 'cncld_driver'
group by state, Request_id)
all_rides as (
select count(*) day_count, status, Request_id
from TRIPS
group by state, Request_id) ,
select cancelled_rides.Request_id as DAY,
(cancelled_rides.cancel_count/all_rides.day_count) as 'Cancellation Rate'
FROM cancelled_rides, all_rides;
这看起来对吗? 注意我故意忽略了包括日期范围,因为该表只有有限的条目。
我没有看到 CTE 对这个查询有任何帮助。 只需使用条件聚合:
select t.Request_id as day, count(*) as total,
sum( status = 'cncld_driver' ) as num_cancelled,
avg( status = 'cncld_driver' ) as cancellation_rate
from trips t
where request_id >= '2017-08-01' and
request_id < '2017-08-04'
group by request_id;
调用日期“request_id”相当混乱。 您应该有一个对每一行都是唯一的请求 ID 和一个带有日期/时间的单独列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.