Sql 需要生成;“迄今为止”;来自2个(或更多)不同的“;“从日期开始”;

Sql 需要生成;“迄今为止”;来自2个(或更多)不同的“;“从日期开始”;,sql,sql-server,datetime,sql-order-by,where-clause,Sql,Sql Server,Datetime,Sql Order By,Where Clause,我有一个带有id、价格和起始日期的成本表。我没有“到目前为止”。因此,从2019年1月1日起,项目1的价格可能为一行50英镑,然后从2020年1月1日起,项目1的价格将为第二行55英镑 如果我想知道今天第1项的价格,我不能使用WHERE today>=fromdate和获取今天的价格获取最新日期不大于今天的行: select c.price from cost c where c.id = 'Item1' and c.fromdate = ( select max(fromdate) fro

我有一个带有id、价格和起始日期的成本表。我没有“到目前为止”。因此,从2019年1月1日起,项目1的价格可能为一行50英镑,然后从2020年1月1日起,项目1的价格将为第二行55英镑


如果我想知道今天第1项的价格,我不能使用
WHERE today>=fromdate和获取今天的价格获取最新日期不大于今天的行:

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 c.price
from cost c
where c.id = 'Item1'
and c.fromdate = (
  select max(fromdate) from cost
  where id = c.id and fromdate <= getdate() 
)

参见一个简化的。

正如Peter Schneider所评论的,一个明智的选择是使用窗口函数
lead()
为相同的
id
恢复下一条记录的
fromdate

select 
    t.*, 
    lead(fromdate) over(partition by id order by fromdate) todate
from mytable t
请注意,使用此技术,对于每个
id
具有最高
fromdate
的记录将
todate
设置为
null
。如果要指定默认结束日期,可以使用
coalesce()

您可以将其放在一个视图中:

create view myview as
select 
    t.*, 
    lead(fromdate) over(partition by id order by fromdate) todate
from mytable t
然后,您可以在视图中查询给定项目的当前价格:

select *
from myview
where 
    id = ? 
    and getdate() >= fromdate
    and (todate is null or getdate() < todate)
选择*
从我的观点
哪里
id=?
和getdate()>=fromdate
和(todate为null或getdate()
正如Peter Schneider所评论的,一个明智的选择是使用窗口函数
lead()
来恢复同一
id
的下一条记录的
fromdate

select 
    t.*, 
    lead(fromdate) over(partition by id order by fromdate) todate
from mytable t
请注意,使用此技术,对于每个
id
具有最高
fromdate
的记录将
todate
设置为
null
。如果要指定默认结束日期,可以使用
coalesce()

您可以将其放在一个视图中:

create view myview as
select 
    t.*, 
    lead(fromdate) over(partition by id order by fromdate) todate
from mytable t
然后,您可以在视图中查询给定项目的当前价格:

select *
from myview
where 
    id = ? 
    and getdate() >= fromdate
    and (todate is null or getdate() < todate)
选择*
从我的观点
哪里
id=?
和getdate()>=fromdate
和(todate为null或getdate()
您应该查看函数…从WHERE fromdate中选择TOP 1*。您应该查看函数…从WHERE fromdate中选择TOP 1*