题解 | #返回每个顾客不同订单的总金额#

返回每个顾客不同订单的总金额

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为例的模拟执行过程如下:

  1. 外层查询选择Orders表中的cust_id,即cust1
  2. 子查询中,过滤条件为a.order_num = b.order_num,对应Orders表中order_numOrderItems表中order_num的关联。
  3. 对于OrderItems表中order_numa0002的两条记录,计算每条记录的item_price * quantity,然后对这两个计算结果进行求和,得到total_ordered。 第一条记录:1 * 1100 = 1100第二条记录:1 * 200 = 200总和:1100 + 200 = 1300
  4. 将计算得到的total_ordered值作为一列返回给外层查询,并成为结果集的一部分。
  5. 最后,根据ORDER BY total_ordered DESC的要求,按照total_ordered值从大到小排序。

根据这个过程,对于cust_idcust1,最终的查询结果应该是:

cust1

1300

这个逻辑同样适用于其他cust_id,具体的order_numtotal_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。

全部评论

相关推荐

豆泥🍀:同26届,加油,我也还没找到查看图片
点赞 评论 收藏
分享
喜欢喜欢喜欢:这是我见过最长最臭的简历
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务