描述

我们需要一个顾客 ID 列表,其中包含他们已订购的总金额。
OrderItems表代表订单信息,OrderItems表有订单号:order_num和商品售出价格:item_price、商品数量:quantity
order_num item_price quantity
a0001 10 105
a0002
1 1100
a0002
1 200
a0013
2 1121
a0003
5 10
a0003
1 19
a0003
7 5
Orders表订单号:order_num、顾客id:cust_id
order_num cust_id
a0001 cust10
a0002
cust1
a0003
cust1
a0013
cust2
【问题】
编写 SQL语句,返回顾客 ID(Orders 表中的 cust_id),并使用子查询返回total_ordered 以便返回每个顾客的订单总数,将结果按金额从大到小排序。
提示:你之前已经使用 SUM()计算订单总数。


SELECT cust_id ,total_ordered
FROM Orders AS a
JOIN (
	SELECT order_num,SUM(item_price*quantity)AS total_ordered
	FROM OrderItems
	GROUP BY order_num 
)AS b ON a.order_num=b.order_num
order by total_ordered desc