2013-07-25 44 views
1
CurrencyId LeftCurrencyId RightCurrencyId ExchangeRateAt   ExchangeRate 
1    1    5    2013-06-27 00:51:00.000 39.
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.

根據leftcurrencyid和rightcurrencyid的組合,我需要最近n天每天的最新記錄。使用MS Sql Server獲取最近n天的每日最新紀錄

+3

還有,你試過嗎?順便說一句,哪個SQL Server版本? –

+2

你可以添加輸出應該是什麼樣子?和一些實際的SQL與表和數據太 – gbn

+0

@Panagiotis Kanavos:它是2008 R2 – RookieStacker

回答

0

這裏是我的兩分錢

Select ExchangeRateAt , * from Table1 where ExchangeRateAt in (Select max(ExchangeRateAt) from Table1 Group by cast(ExchangeRateAt as Date)) 
Order by ExchangeRateAt 
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

這組由LeftCurrencyIdRightCurrencyIdExchangeRateAt天沒有時間組件,則發生在當天所有這些組的最新記錄。

你不提是否要N天回從本日或日期不詳,但你可以這樣從CTE定義EXCHANGERATE表中選擇時使用WHERE子句添加。

+0

謝謝你的幫助。 – RookieStacker

+0

不客氣。如果您找到有用的答案,請考慮將其設置爲接受的答案。 –

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