题解 | #计算总和#

整数转化

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

select 
    order_num,
    sum(item_price*quantity) as total_price
from
    OrderItems
group by
    order_num
having
    sum(quantity*item_price)>=1000
order by
    order_num
;

分析

题目要求:

根据订单号聚合,返回订单总价不小于1000 的所有订单号,总价 = item_price 乘以 quantity。

题目关键词:根据订单号聚合 sql关键词:group by 函数,

返回订单总价不小于1000 的所有订单号。 这是一个过滤条件,但这有一个坑 如果,直接这样写SQL语句:

where sum(item_price*quantity)>=1000

咋一看这好像没问题。

但是别忘记了:where后面不能加聚合函数!

回忆sql语法,这时候就想起了having

having也可以对结果进一步过滤,只不过having必须和group by联用。

使用having后,sql代码如下:

having sum(item_price*quantity)>=1000

这样,就符合了MySQL的语法规则。

分析结果

根据题目要求,可得完整的SQL语句,如下:

select
	order_num,sum(item_price*quantity) as total_price
from 
	OrderItems
group by
	order_num
having
	sum(item_price*quantity)>=1000
order by
	order_num
;

注意:需要对结果进行排序。

本题的另一种解法-子查询

select
	order_num,total_price
    from
	(select
     	order_num,sum(item_price*quantity) total_price 
     from
     	OrderItems
		group by
     		order_num) t
where
	total_price>=1000
order by
order_num
;

这种解法主要是使用了from的子查询,大家就当做知识的回顾。

全部评论

相关推荐

06-17 00:26
门头沟学院 Java
程序员小白条:建议换下项目,智能 AI 旅游推荐平台:https://github.com/luoye6/vue3_tourism_frontend 智能 AI 校园二手交易平台:https://github.com/luoye6/vue3_trade_frontend GPT 智能图书馆:https://github.com/luoye6/Vue_BookManageSystem 选项目要选自己能掌握的,然后最好能自己拓展的,分布式这种尽量别去写,不然你只能背八股文了,另外实习的话要多投,尤其是学历不利的情况下,多找几段实习,最好公司title大一点的
点赞 评论 收藏
分享
牛客837006795号:简历抄别人的,然后再投,有反馈就是简历不行,没反馈就是学历不行,多投多改只要技术不差机会总会有的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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