使用MS Sql Server获取最近n天每天的最新记录

时间:2013-07-25 11:52:07

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

CurrencyId  LeftCurrencyId RightCurrencyId    ExchangeRateAt            ExchangeRate 
 1             1             5                2013-06-27 00:51:00.000    39.0123 
 2             3             5                2013-06-26 01:54:00.000    40.0120 
 3             1             5                2013-06-26 00:51:00.000    49.0143 
 4             3             5                2013-06-25 14:51:00.000    33.3123 
 5             3             5                2013-06-25 06:51:00.000    32.0163
 6             1             5                2013-06-25 00:08:00.000    37.0123  

基于leftcurrencyid和rightcurrencyid的组合,我需要最近n天的最新记录。

3 个答案:

答案 0 :(得分:4)

这是一个选项:

with TopPerDay as
(
  select *
    , DayRank = row_number() over (partition by LeftCurrencyId, RightCurrencyId, cast(ExchangeRateAt as date)
                                   order by ExchangeRateAt desc)
   from ExchangeRate
)
select CurrencyId,
  LeftCurrencyId,
  RightCurrencyId ,
  ExchangeRateDay = cast(ExchangeRateAt as date),
  ExchangeRateAt ,
  ExchangeRate
from TopPerDay
where DayRank = 1
order by LeftCurrencyId,
  RightCurrencyId,
  ExchangeRateDay

SQL Fiddle with demo

LeftCurrencyId RightCurrencyId ExchangeRateAt 分组,没有时间组件,然后在当天获取所有这些记录的最新记录基团。

您没有提及您是否希望N天是从当天或未指定的日期开始,但是您可以在从 ExchangeRate 表中进行选择时使用WHERE子句添加此项在CTE定义中。

答案 1 :(得分:0)

这是我的两分钱

Select ExchangeRateAt , * from Table1 where ExchangeRateAt in (Select max(ExchangeRateAt) from Table1 Group by  cast( ExchangeRateAt as Date))
Order by ExchangeRateAt

答案 2 :(得分:0)

此处7最后是最后一天的N天参数(本例中为7)

with T1 as
(
select t.*,
   cast(floor(cast([ExchangeRateAt] as float)) as datetime) as DatePart,  
   ROW_NUMBER() OVER (
          PARTITION BY [LeftCurrencyId],
                       [RightCurrencyId],
                       cast(floor(cast([ExchangeRateAt] as float)) as datetime)
          ORDER BY [ExchangeRateAt] DESC
     ) RowNumber
from t
), T2 as 
(
  select *,
  ROW_NUMBER() OVER (PARTITION BY [LeftCurrencyId],
                                  [RightCurrencyId]
                     ORDER BY DatePart DESC
                    ) as RN  
  from T1 where RowNumber=1
) 

select [CurrencyId],
       [LeftCurrencyId],
       [RightCurrencyId],
       [ExchangeRateAt],
       [ExchangeRate],
       DatePart  
from T2 where RN<=7

SQLFiddle demo

相关问题