LeetCode1251——平均售价

两个表,一个有时间段,有价格,一个有确切售卖时间和当时售出单价。
刚开始的思路是:直接一步到位,先连接,后分组,然后直接单价*数量/sum(数量),但是错了,得出的结果为空。我个人觉着是因为分组之后直接选择了将单价和数量相乘,因为没有包含聚合数组,字段中的多个值无法进行聚合操作。

# Write your MySQL query statement below
select 
    p.product_id `product_id`, 
    p.price*u.units/sum(u.units) `average_price`
from 
    Prices `p` 
    join 
    UnitsSold `u` 
    on p.product_id = u.product_id
where 
    u.purchase_date between p.start_date and u.product_id
group by p.product_id;

官方解题思路:先将id、销售额、销售数量给每个单独拎出来,成一个新表,然后再继续聚合操作
下面是看官方题解给出的代码:

# Write your MySQL query statement below
select 
    product_id,
    round(sum(sales)/sum(units), 2) `average_price`
from(
    select
        Prices.product_id `product_id`,
        Prices.price * UnitsSold.units `sales`,
        UnitsSold.units `units`
    from
        Prices
    join
        UnitsSold on Prices.product_id = UnitsSold.product_id
    where
        UnitsSold.purchase_date between Prices.start_date and Prices.end_date
) T
group by product_id;
posted @ 2022-05-06 16:46  Lazy_tiger  阅读(33)  评论(0编辑  收藏  举报