SSMS-需要从2个(或更多)不同的“起始日期”生成“截止日期”

问题描述 投票:0回答:1

我有一个包含ID,价格和日期的费用表。我没有“到目前为止”。因此,在第一行中,item1的价格从2019年1月1日起将为50英镑,然后从01/01/2020起,item1的价格将为55英镑,在第二行中。

如果我想今天了解项目1的价格,就不能在今天使用WHERE> = fromdate和<= todate。

如何添加“ todate”?下一行的起始日期的前一天是哪里?

理想情况下,需要作为视图来执行此操作,如果可能,要避免创建表/存储的过程?

谢谢

sql sorting date ssms
1个回答
0
投票

获得最新日期不超过今天的行:

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

© www.soinside.com 2019 - 2024. All rights reserved.