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

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

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#
全部评论
方法二这种思路在实际生产应用中是灾难级的代码,占用内存太高了,你用了必会被dba叼的
点赞 回复 分享
发布于 07-04 10:46 浙江

相关推荐

不愿透露姓名的神秘牛友
11-19 14:56
点赞 评论 收藏
分享
11-04 19:05
已编辑
东莞城市学院 单片机
不知道怎么取名字_:你这个要实习两年?哪有这么久的,感觉就是即使你毕业了,但还按实习的话,是不是不用给你缴社保公积金啥的
点赞 评论 收藏
分享
评论
68
7
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务