题目:平均售价
要求:
编写SQL查询以查找每种产品的平均售价。
average_price 应该四舍五入到小数点后两位。查询结果格式如下例所示:
思路:
题目一定要看懂,之前没咋看题目,以为很简单就直接上手,到头来,输出结果一直报错,原来是题目读错了~
- 判断销售数量日期是否在同一个区间,使用between and
- 通过group by 函数将id进行分组,这样计算出来的 价格*销售量就一一对应了
- 保留两位小数,round(数据,n)函数集合,n为保留的小数个数
select p.product_id ,round(sum(p.price*u.units)/sum(u.units),2) average_price from
Prices p join UnitsSold u on p.product_id=u.product_id where u.purchase_date
between p.start_date and p.end_date group by product_id
1075. 项目员工 I-平均年限
题目要求:
员工表,和员工对应的项目project表, 感觉project表查询员工表,并求出项目中,员工的平均工作年限
本来感觉这道题目,没啥问题的,就是两张表的查询,后面发现,如果自己使用select子查询,查出的结果不符合正确答案,就很疑惑,现在也很疑惑
自己的代码:
select a.project_id,
(select round((sum(b.experience_years )/count(a.project_id)),2) from Employee
b where a.employee_id = b.employee_id )
average_years
from Project a group by a.project_id
- 结果
题解1 ,直接查询两张表
看了大佬的代码,没毛病,但是自己的子查询还是没想出来问题的原因
select a.project_id,
round((sum(b.experience_years )/count(a.project_id)),2) average_years
from Project a ,Employee b where a.employee_id = b.employee_id group by
a.project_id
查询2 使用join using
-
第一次使用using,对using解释一下
-
using等价于join操作中的on
使用using必须满足如下两个条件:
1. 查询必须是等值连接。 2. 等值连接中的列必须具有相同的名称和数据类型。(对于left join 和right join 就不太友好了~)
sql: (小白:简直泰酷辣)
select employee_id , round(avg(),2) average_years from project join employee
using (employee_id) group by project_id