力扣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
相关推荐
吃着火锅x唱着歌1 天前
LeetCode 2110.股票平滑下跌阶段的数目
数据结构·算法·leetcode
疋瓞1 天前
C++_STL和数据结构《1》_STL、STL_迭代器、c++中的模版、STL_vecto、列表初始化、三个算法、链表
数据结构·c++·算法
JJJJ_iii1 天前
【左程云算法09】栈的入门题目-最小栈
java·开发语言·数据结构·算法·时间复杂度
Bear on Toilet1 天前
继承类模板:函数未在模板定义上下文中声明,只能通过实例化上下文中参数相关的查找找到
开发语言·javascript·c++·算法·继承
金融小师妹1 天前
多因子AI回归揭示通胀-就业背离,黄金价格稳态区间的时序建模
大数据·人工智能·算法
程序员东岸1 天前
C语言入门指南:字符函数和字符串函数
c语言·笔记·学习·程序人生·算法
小猪咪piggy1 天前
【算法】day2 双指针+滑动窗口
数据结构·算法·leetcode
max5006001 天前
OpenSTL PredRNNv2 模型复现与自定义数据集训练
开发语言·人工智能·python·深度学习·算法
budingxiaomoli1 天前
AVL树知识总结
数据结构·算法
jz-炸芯片的zero1 天前
【Zephyr电源与功耗专题】14_BMS电池管理算法(三重验证机制实现高精度电量估算)
单片机·物联网·算法·zephyr·bms电源管理算法