问题写法+完善

确定最佳顾客的另一种方式(二)

http://www.nowcoder.com/practice/b5766f970ae64ac7944f37f5b47107aa

问题写法

按照上题简单的写法来写的话 这题可以写出如下的sql

select cust_name,sum(item_price*quantity) as total_price
from Orders as t1
inner join OrderItems as t2 on t1.order_num = t2.order_num
inner join Customers as t3 on t1.cust_id = t3.cust_id
group by cust_name
having total_price >= 1000
order by total_price

但是显然以cust_name来group是不妥当的,万一有两个同名的用户就gg了

改进

虽然麻烦了一点,但是正确性最起码有保障

select cust_name, total_price
from Customers
inner join
( 
    select cust_id, sum(item_price * quantity) as total_price
    from Orders
    inner join OrderItems on OrderItems.order_num = Orders.order_num
    group by cust_id
    having total_price >= 1000
) as res
on Customers.cust_id = res.cust_id
order by total_price
全部评论
group by 里面加一个条件就行了,没事少用子查询,实际工作中查询效率差距是很明显的
1 回复 分享
发布于 2025-07-05 15:36 浙江
写的真好,点赞!
1 回复 分享
发布于 2023-04-12 22:36 陕西
GROUP BY c.cust_id, c.cust_name 解决同名用户
点赞 回复 分享
发布于 2025-04-03 22:14 美国
这样写是不是相当于建立了一个临时表作为联结?
点赞 回复 分享
发布于 2025-03-31 18:03 北京

相关推荐

评论
22
2
分享

创作者周榜

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