力扣SQL50 指定日期的产品价格 双重子查询 coalesce

Problem: 1164. 指定日期的产品价格

  • coalesce 的使用

简洁版

👨‍🏫 参考题解

MySQL 复制代码
select 
    distinct p1.product_id,
    coalesce((select p2.new_price
    from Products p2
    where p2.product_id = p1.product_id and p2.change_date <= '2019-08-16'
    order by p2.change_date DESC
    limit 1),10) as price 
from Products p1

高效版

👨‍🏫 参考题解

java 复制代码
select p1.product_id, ifnull(p2.new_price, 10) as price
from (
    select distinct product_id
    from products
) as p1 -- 所有的产品
left join (
    select product_id, new_price 
    from products
    where (product_id, change_date) in (
        select product_id, max(change_date)
        from products
        where change_date <= '2019-08-16'
        group by product_id
    )
) as p2 -- 在 2019-08-16 之前有过修改的产品和最新的价格
on p1.product_id = p2.product_id
相关推荐
黄昏ivi1 小时前
电力系统最小惯性常数解析
算法
独家回忆3641 小时前
每日算法-250425
算法
烁3471 小时前
每日一题(小白)模拟娱乐篇33
java·开发语言·算法
Demons_kirit2 小时前
LeetCode 2799、2840题解
算法·leetcode·职场和发展
软行2 小时前
LeetCode 每日一题 2845. 统计趣味子数组的数目
数据结构·c++·算法·leetcode
永远在Debug的小殿下2 小时前
查找函数【C++】
数据结构·算法
我想进大厂2 小时前
图论---染色法(判断是否为二分图)
数据结构·c++·算法·深度优先·图论
油泼辣子多加2 小时前
【风控】稳定性指标PSI
人工智能·算法·金融
雾月553 小时前
LeetCode 1292 元素和小于等于阈值的正方形的最大边长
java·数据结构·算法·leetcode·职场和发展
OpenC++4 小时前
【C++QT】Buttons 按钮控件详解
c++·经验分享·qt·leetcode·microsoft