题解 | #返回每个顾客不同订单的总金额#(这样或许才对?)

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

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

SELECT cust_id, 
       SUM((SELECT SUM(quantity*item_price) # 新增SUM
        FROM OrderItems
        WHERE OrderItems.order_num = Orders.order_num)) AS total_ordered
FROM Orders
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;
 # 这种做法,只是统计了表中的每一行顾客对应订单的总金额 没有考虑到多行的顾客可能是一样的(比如题目例子,有两个cust1(当然,题目例子答案的第二个cust2应该是cust1))
*/

应该在热评的基础上修改一下,使用分组查询,考虑顾客id可能一样的情况(题目例子就是)

全部评论

相关推荐

点赞 1 评论
分享
牛客网
牛客企业服务