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 @   Lazy_tiger  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示