【问题标题】:How to select last updated row until specific date?如何选择特定日期之前的最后更新行?
【发布时间】:2025-12-29 11:30:06
【问题描述】:

我们有三个 ProductID,它们的价格按日期变化

ProductID   Price       Date
1            100      2016-06-01
2            50       2016-06-05
3            10       2016-06-10
2            60       2016-06-15
1            110      2016-06-20
3            20       2016-06-25

如何选择在 2016 年 6 月 20 日(含)之前每个 ProductID 的最后更新价格以获得下一个输出:

ProductID   Price
3            10
2            60
1            110

我搜索了答案,但找不到具体的答案。

【问题讨论】:

  • 将您的问题与您正在使用的数据库联系起来。

标签: sql


【解决方案1】:

有一个子查询返回每个 ProductID 的最后日期(直到 2016 年 6 月 20 日)。加入该结果:

select t1.*
from tablename t1
  join (select ProductID, max(Date) Date
        from tablename
        where Date <= '2016-06-20'
        group by ProductID) t2
    on t1.ProductID = t2.ProductID and t1.Date = t2.Date

ANSI SQL 将date 作为保留字,因此您可能需要将该列分隔为"Date"。此外,ANSI SQL 的日期文字为 date '2016-06-20'

【讨论】: