题解 | #返回每个顾客不同订单的总金额#
返回每个顾客不同订单的总金额
https://www.nowcoder.com/practice/ce313253a81c4947b20e801cd4da7894
# 参考了一下其他人的代码:
解1:先在OrderItems中计算每个订单的总额,使用WITH 表名 AS () 新建一个表。
将新表与Orders表连接,根据订单总额降序排列,返回cust_id。
WITH total_order_price AS( SELECT order_num, SUM(item_price * quantity) total_ordered FROM OrderItems GROUP BY order_num ) SELECT o.cust_id, tp.total_ordered FROM Orders o LEFT JOIN total_order_price tp ON o.order_num = tp.order_num ORDER BY tp.total_ordered DESC;
解2:使用子查询
1) 基础版子查询
SELECT b.cust_id cust_id, a.total_ordered total_ordered FROM Orders b,( SELECT order_num, SUM(item_price*quantity) total_ordered FROM OrderItems GROUP BY order_num ) a WHERE b.order_num = a.order_num ORDER BY total_ordered DESC;
2) 最简洁的子查询写法
SELECT cust_id, (SELECT SUM(item_price * quantity) FROM OrderItems a WHERE a.order_num = b.order_num) total_ordered #聚合的字段放在select后,用where+关联条件关联即可 FROM Orders b ORDER BY total_ordered DESC;