• 1251. 平均售价


    Table: Prices

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

    Table: UnitsSold

    +---------------+---------+
    | Column Name | Type |
    +---------------+---------+
    | product_id | int |
    | purchase_date | date |
    | units | int |
    +---------------+---------+
    UnitsSold 表没有主键,它可能包含重复项。
    UnitsSold 表的每一行表示的是每种产品的出售日期,单位和产品 id。

    解题方法:

    select product_id, round(sum(price*units)/sum(units),2) as average_price from
    (
    select a.product_id as product_id, price,units from Prices a
    join UnitsSold b
    on a.product_id = b.product_id and b.purchase_date BETWEEN a.start_date AND a.end_date
    ) as c
    group by product_id
  • 相关阅读:
    MySQL 处理重复数据
    MySQL 序列使用
    MySQL 元数据
    MySQL 临时表和复制表
    MySQL 索引
    MySQL ALTER命令-修改数据表名或者修改数据表字段
    MySQL 事务
    MySQL 正则表达式
    MySQL NULL 值处理
    MySQL 排序
  • 原文地址:https://www.cnblogs.com/tomorrow-hope/p/13834407.html
Copyright © 2020-2023  润新知