在sql server上获取最近的日期值

时间:2013-11-14 07:59:40

标签: sql sql-server sql-server-2008

我需要找到特定日期的期末余额。表结构如下

    MainCode    TranDate    Balance
    930000003   2013-11-06  564481526.51
    930000003   2013-11-07  571703938.55
    930000003   2013-11-08  571690438.55
    930000003   2013-11-10  551992179.45

当我开火时

select
 Trandate,Balance 
from tbl where MainCode='930000003' and
TranDate ='2013-11-06' 

然后它将返回564481526.51 但问题是 2013-11-09 上没有交易,在这种情况下我必须取2013-11-08的余额,如果2013-11-08也没有交易那么我必须取得2013-11-07的余额等等..即如果在指定日期没有交易,我必须取最近(过去)日期交易的余额

2 个答案:

答案 0 :(得分:2)

您可以按日期订购数据,并使用top

获取第一条记录
select top 1 Trandate,Balance 
from tbl 
where MainCode='930000003' 
and TranDate <= '2013-11-09' 
order by TranDate desc

答案 1 :(得分:0)

您可以将子查询用于按TranDate降序排序的日期。

select Trandate,Balance 
from tbl t1
where t1.MainCode='930000003' 
and t1.TranDate = (SELECT TOP 1 TranDate FROM tbl t2
                   WHERE t1.MainCode=t2.MainCode
                   AND   t2.TranDate <= '2013-11-09'
                   ORDER BY TranDate DESC)

Demo