题解 | #返回每个顾客不同订单的总金额#
返回每个顾客不同订单的总金额
https://www.nowcoder.com/practice/ce313253a81c4947b20e801cd4da7894
整理了一下 子查询的方法,其中方法三、四很像,有点重复。
感觉题目给的示例是错误的,cust2不应该有两行,所以很多子查询(从OrderItems里)形成子表的时候group by order_num完了都应该是只有一个cust2的,有一个评论说如果想要两个cust2就需要在方法一里改成group by cust_id, order_num。
还有我很疑惑MySQL的注释不是--吗为啥这里是#😂
# 方法一:最简单的方法
select cust_id, sum(quantity*item_price) as total_ordered
from Orders join OrderItems using(order_num)
group by cust_id #注意要group否则有歧义
order by total_ordered desc;
# 方法二:先选列,再利用子查询选子列
select cust_id,
# 从列里自定义子查询语句
(
select sum(quantity*item_price)
from OrderItems oi
where oi.order_num = o.order_num
) as total_ordered
from Orders o
order by total_ordered desc;
# 方法三:从表与子表(子查询生成的表)找
select cust_id, total_ordered
from Orders a,
(
select order_num, sum(quantity*item_price) total_ordered
from OrderItems
group by order_num #注意生成子表时需要group
) as t
where t.order_num = a.order_num
order by total_ordered desc;
# 方法四:表与子表联结(join)
select cust_id, total_ordered from Orders a
left join
(
select order_num, sum(quantity*item_price) as total_ordered
from OrderItems
group by order_num #注意生成子表时需要group
) as b
on a.order_num = b.order_num
order by total_ordered desc;
#题解##MySQL##sql#
