题解 | #返回每个顾客不同订单的总金额#
返回每个顾客不同订单的总金额
https://www.nowcoder.com/practice/ce313253a81c4947b20e801cd4da7894
select od.cust_id, sum(ot.item_price * ot.quantity) AS total_order from Orders AS od JOIN OrderItems AS ot ON od.order_num = ot.order_num GROUP BY od.cust_id ORDER BY total_order DESC
以cust1
为例的模拟执行过程如下:
- 外层查询选择
Orders
表中的cust_id
,即cust1
。 - 子查询中,过滤条件为
a.order_num = b.order_num
,对应Orders
表中order_num
与OrderItems
表中order_num
的关联。 - 对于
OrderItems
表中order_num
为a0002
的两条记录,计算每条记录的item_price * quantity
,然后对这两个计算结果进行求和,得到total_ordered
。 第一条记录:1 * 1100 = 1100第二条记录:1 * 200 = 200总和:1100 + 200 = 1300 - 将计算得到的
total_ordered
值作为一列返回给外层查询,并成为结果集的一部分。 - 最后,根据
ORDER BY total_ordered DESC
的要求,按照total_ordered
值从大到小排序。
根据这个过程,对于cust_id
为cust1
,最终的查询结果应该是:
cust1 | 1300 |
这个逻辑同样适用于其他cust_id
,具体的order_num
和total_ordered
的值会根据数据进行相应的计算。整个查询过程就是对每个cust_id
计算其相应的total_ordered
,并按照total_ordered
值进行排序。
内连接
select od.cust_id, sum(ot.item_price * ot.quantity) AS total_order from Orders AS od JOIN OrderItems AS ot ON od.order_num = ot.order_num GROUP BY od.cust_id ORDER BY total_order DESC
题目
我们需要一个顾客 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 | cust 10 |
a0002 | cust 1 |
a0003 | cust 1 |
a0013 | cust 2 |
【问题】
编写 SQL语句,返回顾客 ID(Orders 表中的 cust_id),并使用子查询返回total_ordered 以便返回每个顾客的订单总数,将结果按金额从大到小排序。
提示:你之前已经使用 SUM()计算订单总数。
【示例结果】返回顾客id cust_id和total_order下单总额
cust_id | total_ordered |
cust2 | 2242 |
cust 1 | 1300 |
cust 10 | 1050 |
cust 2 | 104 |
【示例解析】cust2在Orders里面的订单a0013,a0013的售出价格是2售出数量是1121,总额是2242,最后返回cust2的支付总额是2242。