无法获取 SQL 服务器子查询以选择所需的结果

Trouble getting SQL Server subquery to pick desired results

我得到了一个在 SQL 服务器中使用的数据库。 table 是:

我需要确定每个产品的 ID 和当前价格。

Price table 中的 from 属性是价格更新的日期,即 table 中的每个 ID 都有多个与之关联的价格和日期但所有 ID 之间没有共同的日期,日期采用 'YYYY-MM-DD' 格式,范围是从 2018 年到 2019-12-31。

我当前的查询如下:

select distinct p.prodID, p.price
from Price as p
where p.[from] >= '2019-12-23' and p.[from] in (select [from]
from Price
group by [from]
having max([from]) <= '2019-12-31')
order by p.prodID;

其中 returns 一个 table 对某些 ID 有多个价格,并且还完全排除了其他 ID。

我被告知我需要一个子查询来执行此操作。

我认为我的查询可能过于具体,无法生成所需的结果。

我的主要目标是将我当前的查询修复为 select 每个 prodIDprice 中的一个,从最近的 from 日期开始。

一个选项使用 window 个函数:

select *
from (
    select p.*, row_number() over(partition by p.prodid order by p.from desc) rn
    from price p
    where p.from <= convert(date, getdate())
) t
where rn = 1

这 returns 每个 prodid 的最新行,其中 from 不早于当前日期。

作为替代方案,您也可以使用 with ties:

select top (1) with ties p.*
from price p
where p.from <= convert(date, getdate())
order by row_number() over(partition by p.prodid order by p.from desc)