1
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 天的每一天的最新记录。

4

3 回答 3

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 与演示

它按没有时间组件的LeftCurrencyIdRightCurrencyIdExchangeRateAt天分组,然后为所有这些组获取当天的最新记录。

您没有提及是否希望 N 天后是从今天开始还是未指定的日期,但是您可以在从CTE 定义中的ExchangeRateWHERE表中选择时使用子句添加它。

于 2013-07-25T12:09:29.100 回答
0

这是我的两分钱

Select ExchangeRateAt , * from Table1 where ExchangeRateAt in (Select max(ExchangeRateAt) from Table1 Group by  cast( ExchangeRateAt as Date))
Order by ExchangeRateAt
于 2013-07-25T12:08:59.847 回答
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 演示

于 2013-07-25T12:17:33.063 回答