Mysql 如何返回一列中的日期与另一列中的日期最接近(但不超过)的行

Mysql 如何返回一列中的日期与另一列中的日期最接近(但不超过)的行,mysql,sql,where-clause,Mysql,Sql,Where Clause,我继承了一个数据库,它可以跟踪——在大量其他信息中——一段时间内的单价和特定产品的订单。我需要我的查询只返回列effectiveDate中的值最接近的行,而不超过列OrderDate中的值(以便在下单时查找unitprice)。链接图像显示我的查询的最新迭代及其结果。我还尝试了按puph.productID分组,但返回的结果是最早的有效日期,而不是最晚的有效日期 简言之,如何仅返回在执行OrderDate时具有最新effectiveDate的行 mysql v8.0,您可以使用行号() 为什么是

我继承了一个数据库,它可以跟踪——在大量其他信息中——一段时间内的单价和特定产品的订单。我需要我的查询只返回列
effectiveDate
中的值最接近的行,而不超过列
OrderDate
中的值(以便在下单时查找
unitprice
)。链接图像显示我的查询的最新迭代及其结果。我还尝试了
按puph.productID分组,但返回的结果是最早的
有效日期,而不是最晚的
有效日期

简言之,如何仅返回在执行
OrderDate
时具有最新
effectiveDate
的行


mysql v8.0,您可以使用
行号()


为什么是mysql版本?这不是一个完整的问题,因为您忽略了包含代码。请这样做。第一种方法似乎有效,但
rn
列不会迭代。这是预期的吗?取决于分区,请尝试将其更改为o.orderID
select * from (select o.OrderID, o.OrderDate, puph.productID, puph.unitprice, puph.effectiveDate
        , row_number() over (partition by o.orderID order by puph.effectiveDate desc) as rn
    from orders orders
    join `order details` od on o.OrderID = od.OrderID
    join productunitpricehistory puph on od.ProductID = puph.productID
    where puph.effectiveDate <= o.OrderDate
    ) t1
where t1.rn = 1
order by t1.OrderID
select o.OrderID, o.OrderDate, puph.productID, puph.unitprice
, max(puph.effectiveDate) as effectiveDate
from orders orders
join `order details` od on o.OrderID = od.OrderID
join productunitpricehistory puph on od.ProductID = puph.productID
where puph.effectiveDate <= o.OrderDate
group by o.OrderID, o.OrderDate, puph.productID, puph.unitprice
order by o.OrderID