**难 题解 | #返回每个顾客不同订单的总金额#
返回每个顾客不同订单的总金额
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错题 文章被收录于专栏
每天学习一遍 刷题刷题 越刷越强!