SQL选择值按每天的最大时间

时间:2013-08-27 08:59:40

标签: sql

DBMS: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]每日的费率?

输出结果为:

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

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

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

4 个答案:

答案 0 :(得分: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;

答案 1 :(得分:2)

对于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年以下的任何事情,请查看here

答案 2 :(得分:0)

你可以这样做,请阅读format这里

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


//101 = mm/dd/yyyy - 10/02/2008

答案 3 :(得分:0)

对于MySQL:

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

查看有关aggregate functions的更多信息。

其他RDBMS可能不支持这个(我知道PostgreSQL没有)。