mysql查询按时间选择最后一条记录

时间:2015-11-02 07:20:44

标签: mysql

我有这样的表: 表 exchaneRate

╔════╦══════════╦══════════════╦═════╦══════╦══════════════════╗
║ id ║ officeID ║ currencyCode ║ buy ║ sell ║ startDateTime    ║
╠════╬══════════╬══════════════╬═════╬══════╬══════════════════╣
║ 01 ║  off_1   ║       AA     ║  65 ║  75  ║ 2015═10═01 12:00 ║
╠════╬══════════╬══════════════╬═════╬══════╬══════════════════╣
║ 02 ║  off_1   ║       BB     ║  64 ║  73  ║ 2015═10═01 12:00 ║
╠════╬══════════╬══════════════╬═════╬══════╬══════════════════╣
║ 03 ║  off_1   ║       AA     ║  55 ║  65  ║ 2015═09═25 12:00 ║
╠════╬══════════╬══════════════╬═════╬══════╬══════════════════╣
║ 04 ║  off_1   ║       BB     ║  54 ║  63  ║ 2015═09═25 12:00 ║
╠════╬══════════╬══════════════╬═════╬══════╬══════════════════╣
║ 05 ║  off_1   ║       AA     ║  30 ║  42  ║ 2015═09═15 12:00 ║
╠════╬══════════╬══════════════╬═════╬══════╬══════════════════╣
║ 06 ║  off_1   ║       BB     ║  40 ║  48  ║ 2015═09═15 12:00 ║
╠════╬══════════╬══════════════╬═════╬══════╬══════════════════╣
║ 07 ║  off_2   ║       AA     ║  65 ║  75  ║ 2015═10═01 12:00 ║
╠════╬══════════╬══════════════╬═════╬══════╬══════════════════╣
║ 08 ║  off_2   ║       BB     ║  65 ║  75  ║ 2015═10═01 12:00 ║
╚════╩══════════╩══════════════╩═════╩══════╩══════════════════╝

我这样请求选择数据:

    select `currencyCode`, `buy`, `sell` from `exchangeRate` 
where `officeID` = 'off_1' and startDateTime <= '2015-09-30 00:00';

我想要这个结果:

╔══════════════╦═════╦══════╗
║ currencyCode ║ buy ║ sell ║
╠══════════════╬═════╬══════╣
║       AA     ║  55 ║  65  ║
╠══════════════╬═════╬══════╣
║       BB     ║  54 ║  63  ║
╚══════════════╩═════╩══════╝

但是请求从表中返回所有记录AA,BB,AA,BB,AA,BB ....但我需要为此currencyCode的每个officeID提供最后一条记录。 我怎么能这样做?

3 个答案:

答案 0 :(得分:1)

试试这个

select `currencyCode`, `buy`, `sell` from `exchangeRate` 
where id in 
( select max(id) from exchangeRate  
   where `officeID` = 'off_1' and startDateTime <= '2015-09-30 00:00' group by currencyCode 
)

SQLFIDDLE

答案 1 :(得分:0)

我会采用以下方法。内部查询使用您的时间范围确定每个currencyCode所需的记录。然后,通过exchangeRate对此内部查询过滤原始INNER JOIN表,以提供所需的输出。

SELECT t1.currencyCode, t1.buy, t1.sell
FROM exchangeRate t1 INNER JOIN
(
    SELECT currencyCode, MAX(startDateTime) AS maxTime
    FROM exchangeRate
    WHERE startDateTime <= '2015-09-30 00:00' AND officeID = 'off_1'
    GROUP BY currencyCode
) t2
ON t1.currencyCode = t2.currencyCode AND t1.startDateTime = t2.maxTime

点击下方查看正在运行的演示。

SQLFiddle

答案 2 :(得分:0)

试试这个

SELECT currencyCode,
 SUBSTRING_INDEX(GROUP_CONCAT(buy ORDER BY startDateTime DESC),',',1) as buy_1,
 SUBSTRING_INDEX(GROUP_CONCAT(sell ORDER BY startDateTime DESC),',',1) as sell_1,
 SUBSTRING_INDEX(GROUP_CONCAT(startDateTime ORDER BY startDateTime DESC),',',1) as date_1 
FROM exchangeRate
WHERE officeID = 'off_1'
GROUP BY currencyCode
HAVING date_1 <= '2015-09-30 00:00'
ORDER BY currencyCode 
相关问题