题解 | #计算总和#

整数转化

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-27 15:07
点赞 评论 收藏
分享
06-11 13:34
门头沟学院 C++
offe从四面八方来:我真的没时间陪你闹了
点赞 评论 收藏
分享
06-12 17:46
门头沟学院 Java
运营你豪哥:来说重点: ​1.项目前置,时间倒序。​​ 2.​项目描述强化结果与量化效果(STAR原则里的R)。​​ ​3.个人技能精炼,明确掌握程度,突出核心。​​ ​4.增加强有力开头的个人总结部分。​​ 5.​优化教育背景(成绩排名)、合并奖项与活动。​​
听劝,我这个简历该怎么改...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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