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

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

https://www.nowcoder.com/practice/ce313253a81c4947b20e801cd4da7894



select cust_id,
    sum(item_price*quantity)  AS total_ordered
FROM Orders a, OrderItems b 
where a.order_num =b.order_num
group by cust_id
order by  total_ordered DESC;



select cust_id,
(select sum(quantity * item_price) 
    from  OrderItems
    where OrderItems.order_num=Orders.order_num
) AS total_ordered
from Orders 
order by total_ordered DESC;




# 方法一:最简单的方法
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;







SQL错题 文章被收录于专栏

每天学习一遍 刷题刷题 越刷越强!

全部评论

相关推荐

程序员小白条:你不是有一段实习了吗,现在找中大厂实习?过段时间要秋招了
我的简历长这样
点赞 评论 收藏
分享
07-03 11:02
中山大学 C++
字节刚oc,但距离九月秋招很近了有两段互联网实习,非腾讯字节。不敢赌转正,现在在纠结去还是不去如果实习俩月离职会有什么后果吗
阿城我会做到的:不去后悔一辈子,能否转正取决于ld的态度,只要他不卡,答辩就是走流程,个人觉得可以冲一把
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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