1

数据库管理系统:MS SQL 2005

以下表为例

[CurrencyID] ---- [Rate] ---- [ExchangeDate]

USD --------------- 1 ------ 08/27/2012 11:52 AM

USD -------------- 1.1 ----- 08/27/2012 11:58 AM

USD -------------- 1.2 ----- 08/28/2012 01:30 PM

USD --------------- 1 ------ 08/28/2012 01:35 PM

如何获取每种货币的最新 [ExchangeDate] Per Day汇率?

输出将是:

 [CurrencyID] ---- [Rate] ---- [ExchangeDate]

    USD ----------- 1.1 ------- 08/27/2012

    USD ------------ 1 -------- 08/28/2012
4

4 回答 4

3

您没有指定哪个 DBMS,以下是标准 SQL:

select CurrencyID, Rate, ExchangeDate
from
  (
    select CurrencyID, Rate, ExchangeDate,
       row_number() 
       over (partition by CurrencyID, cast(ExchangeDate as date)
             order by ExchangeDate desc) as rn
    from tab
  ) as dt
 where rn = 1;
于 2013-08-27T09:05:12.290 回答
3

对于 SQL 2008,以下方法可以解决问题:

SELECT  CurrencyID, cast(ExchangeDate As Date) as ExchangeDate , (
          SELECT   TOP 1 Rate
          FROM     Table T2
          WHERE    cast(T2.ExchangeDate  As Date) = cast(T1.ExchangeDate  As Date)
          AND      T2.CurrencyID = T1.CurrencyID
          ORDER BY ExchangeDate DESC) As LatestRate
FROM    Table T1
GROUP BY CurrencyID, cast(T1.ExchangeDate  As Date)

对于 2008 年以下的任何内容,请查看此处

于 2013-08-27T09:11:49.083 回答
0

你可以这样做,在这里阅读格式

select * from exchangetable order by convert(datetime, ExchangeDate, 101) ASC desc


//101 = mm/dd/yyyy - 10/02/2008
于 2013-08-27T09:03:57.503 回答
0

对于 MySQL:

SELECT Rate, MAX(ExchangeDate) FROM table GROUP BY DATE(ExchangeDate)

查看有关聚合函数的更多信息。

其他 RDBMS 可能不支持这一点(我知道 PostgreSQL 不支持)。

于 2013-08-27T09:04:40.140 回答