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

对于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年以下的任何内容,请查看此处。

您没有指定哪个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;

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

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

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

对于MySQL:

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

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

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

最新更新