有取消订单记录的司机平均评分

明确题意:

找到2021年10月有过取消订单记录的司机,计算他们每人全部已完成的有评分订单的平均评分及总体平均评分,保留1位小数。


问题分解:

  • 找出2021年10月有取消订单的司机:WHERE DATE_FORMAT(order_time, "%Y-%m")='2021-10' AND ISNULL(fare)
  • 筛选他们的已完成订单的评分:WHERE driver_id in (...) AND NOT ISNULL(grade)
  • 按司机分组:GROUP BY driver_id
  • 追加汇总信息:WITH ROLLUP
  • 输出每个司机的平均评分:
    • 司机ID或总体:IFNULL(driver_id, "总体") as driver_id
    • 平均评分:AVG(grade) as avg_grade
    • 保留1位小数:ROUND(x, 1)

细节问题:

  • 表头重命名:as

完整代码:

SELECT IFNULL(driver_id, "总体") as driver_id,
    ROUND(AVG(grade), 1) as avg_grade
FROM tb_get_car_order
WHERE driver_id in (
    SELECT driver_id
    FROM tb_get_car_order
    WHERE DATE_FORMAT(order_time, "%Y-%m")='2021-10' AND ISNULL(fare)
) AND NOT ISNULL(grade)
GROUP BY driver_id
WITH ROLLUP;