检查这个材料
同样的 180,两种平均数 材料: sql · 4 条注释
1 WITH paid_march_lines(line_id, order_id, product, quantity, 2 unit_price) AS ( 3 VALUES 4 ( 2, 102, 'Kettle', 1, 30), 5 ( 3, 102, 'Tea tin', 2, 12), 6 ( 4, 103, 'Mug', 1, 8), 7 ( 5, 103, 'Tea tin', 1, 12), 8 ( 6, 103, 'Filter', 3, 4), 9 ( 9, 106, 'Mug', 4, 8), 10 (10, 106, 'Filter', 2, 4), 11 (11, 107, 'Tea tin', 1, 12), 12 (12, 107, 'Mug', 1, 8), 13 (13, 108, 'Kettle', 1, 30), 14 (14, 108, 'Filter', 1, 4) 15 ), 16 order_totals AS ( 17 SELECT order_id, SUM(quantity * unit_price) AS order_total 18 FROM paid_march_lines 19 GROUP BY order_id 20 ) 21 SELECT 'average of the 11 line totals' AS method, 22 ROUND(AVG(quantity * unit_price), 2) AS value 23 FROM paid_march_lines 24 UNION ALL 25 SELECT 'average of the 5 order totals', 26 ROUND(AVG(order_total), 2) 27 FROM order_totals; 先改粒度 第 16–20 行 GROUP BY order_id 把每个订单的明细加成一行,每个订单一行。就是这一步把明细级的数据变成了订单级的数据。
对明细求平均 第 21–22 行 对每条明细的金额求 AVG。拿它回答“一条明细平均多少钱”是对的,拿它回答平均订单金额就错了。这是故意写错的。
四舍五入 第 22 行 ROUND(..., 2) 保留两位小数,所以 180 除以 11 显示为 16.36。
对订单求平均 第 25–26 行 对五个订单合计求 AVG,每个订单一行。这才是经理要的数。
预期输出: method value
----------------------------- -----
average of the 11 line totals 16.36
average of the 5 order totals 36.0
材料包含 27 行和 4 条注释。