我有一个包含ID,价格和日期的费用表。我没有“到目前为止”。因此,在第一行中,item1的价格从2019年1月1日起将为50英镑,然后从01/01/2020起,item1的价格将为55英镑,在第二行中。
如果我想今天了解项目1的价格,就不能在今天使用WHERE> = fromdate和<= todate。
如何添加“ todate”?下一行的起始日期的前一天是哪里?
理想情况下,需要作为视图来执行此操作,如果可能,要避免创建表/存储的过程?
谢谢
获得最新日期不超过今天的行:
select c.price
from cost c
where c.id = 'Item1'
and c.fromdate = (
select max(fromdate) from cost
where id = c.id and fromdate <= getdate()
)
或:
select top 1 price
from cost
where id = 'Item1' and fromdate <= getdate()
order by fromdate desc
请参阅简化的demo。