题目链接:点击打开链接
题目大意:略。
解题思路:题目英文描述,其实就是比上一题计算 accepted_rides 时,不是全部符合的司机,而是不同的司机,所以需要去重。
WITH RECURSIVE cal AS( SELECT 1 month UNION ALL SELECT month + 1 FROM cal WHERE month < 12 ), # 计算 active_drivers t1 AS(SELECT month, COUNT(*) active_drivers FROM cal LEFT JOIN Drivers ON DATEDIFF(CONCAT('2020-', month, '-1'), DATE_FORMAT(join_date, '%Y-%m-1')) >= 0 WHERE join_date < '2021-1-1' GROUP BY month), # 计算 accepted_rides t2 AS(SELECT month, COUNT(DISTINCT driver_id) accepted_rides FROM cal LEFT JOIN Drivers ON DATEDIFF(CONCAT('2020-', month, '-1'), DATE_FORMAT(join_date, '%Y-%m-1')) >= 0 LEFT JOIN (Rides JOIN AcceptedRides USING(ride_id)) USING(driver_id) WHERE requested_at BETWEEN '2020-01-01' AND '2020-12-31' AND month = MONTH(requested_at) GROUP BY month), # 合并 t3 AS(SELECT month, active_drivers, 0 accepted_rides FROM t1 UNION ALL SELECT month, 0 active_drivers, accepted_rides FROM t2 UNION ALL SELECT month, 0 active_drivers, 0 accepted_rides FROM cal) SELECT month, IFNULL(ROUND(SUM(accepted_rides) / SUM(active_drivers) * 100, 2), 0) working_percentage FROM t3 GROUP BY month ORDER BY month