【LeetCode】1251. 平均售价

表:Prices

复制代码
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| start_date    | date    |
| end_date      | date    |
| price         | int     |
+---------------+---------+
(product_id,start_date,end_date) 是 prices表的主键(具有唯一值的列的组合)。
prices表的每一行表示的是某个产品在一段时期内的价格。
每个产品的对应时间段是不会重叠的,这也意味着同一个产品的价格时段不会出现交叉。

表:UnitsSold

复制代码
+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| purchase_date | date    |
| units         | int     |
+---------------+---------+
该表可能包含重复数据。
该表的每一行表示的是每种产品的出售日期,单位和产品 id。

编写解决方案以查找每种产品的平均售价。average_price 应该 四舍五入到小数点后两位

返回结果表 无顺序要求

结果格式如下例所示。

示例 1:

复制代码
输入:
Prices table:
+------------+------------+------------+--------+
| product_id | start_date | end_date   | price  |
+------------+------------+------------+--------+
| 1          | 2019-02-17 | 2019-02-28 | 5      |
| 1          | 2019-03-01 | 2019-03-22 | 20     |
| 2          | 2019-02-01 | 2019-02-20 | 15     |
| 2          | 2019-02-21 | 2019-03-31 | 30     |
+------------+------------+------------+--------+
UnitsSold table:
+------------+---------------+-------+
| product_id | purchase_date | units |
+------------+---------------+-------+
| 1          | 2019-02-25    | 100   |
| 1          | 2019-03-01    | 15    |
| 2          | 2019-02-10    | 200   |
| 2          | 2019-03-22    | 30    |
+------------+---------------+-------+
输出:
+------------+---------------+
| product_id | average_price |
+------------+---------------+
| 1          | 6.96          |
| 2          | 16.96         |
+------------+---------------+
解释:
平均售价 = 产品总价 / 销售的产品数量。
产品 1 的平均售价 = ((100 * 5)+(15 * 20) )/ 115 = 6.96
产品 2 的平均售价 = ((200 * 15)+(30 * 30) )/ 230 = 16.96
sql 复制代码
select
Prices.product_id,
ifnull(round(sum(price*units)/sum(units),2),0) as average_price
from
Prices left join UnitsSold 
on Prices.product_id=UnitsSold.product_id
and UnitsSold.purchase_date between Prices.start_date and Prices.end_date
group by Prices.product_id
相关推荐
2301_768350234 分钟前
MySQL服务配置与管理
数据库·mysql
百锦再14 分钟前
国产数据库的平替亮点——关系型数据库架构适配
android·java·前端·数据库·sql·算法·数据库架构
练习时长一年44 分钟前
LeetCode热题100(搜索插入位置)
数据结构·算法·leetcode
凌睿马1 小时前
关于复杂数据结构从MySQL迁移到PostgreSQL的可行性
数据结构·数据库·mysql
星光一影1 小时前
美容/心理咨询/问诊/法律咨询/牙医预约/线上线下预约/牙医行业通用医疗预约咨询小程序
mysql·小程序·vue·php·uniapp
IT枫斗者1 小时前
Netty的原理和springboot项目整合
java·spring boot·后端·sql·科技·mysql·spring
(●—●)橘子……2 小时前
记力扣557.反转字符串中的单词 练习理解
算法·leetcode·职场和发展
Hello.Reader2 小时前
Flink SQL ALTER 语句在线演进 Table/View/Function/Catalog/Model
数据库·sql·flink
总有刁民想爱朕ha2 小时前
MySQL 8 Windows日常维护教程(安装、备份、还原、重置密码等)
windows·mysql
元气满满-樱2 小时前
MySql部署多实例
数据库·mysql·adb