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

1 つのオプションを次に示します。

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

demo を使用した SQL Fiddle

時間コンポーネントなしでLeftCurrencyIdRightCurrencyId、およびExchangeRateAt日でグループ化し、それらすべてのグループについてその日の最新のレコードを取得します。

N 日後が現在の日付または未指定の日付のどちらであるかについては言及していませんが、CTE 定義のExchangeRateテーブルWHEREから選択するときに句を使用してこれを追加できます。

于 2013-07-25T12:09:29.100 に答える
0

これが私の2セントです

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 に答える