檢查這份材料
同樣的 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 則註解。