2015-11-02 60 views
1

只选择最后一个记录我的表是这样的: 表exchaneRateMySQL查询的时间

╔════╦══════════╦══════════════╦═════╦══════╦══════════════════╗ 
║ 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 ║ 
╚══════════════╩═════╩══════╝ 

但是请求返回所有re表AA,BB,AA,BB,AA,BB ...。但是我需要这officeID的每个currencyCode的最后记录。 我该怎么做?

+0

你是如何创建的结果集目前尚不清楚。你想如何为每个'currencyCode'选择一条记录? –

回答

0

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

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

+0

http://sqlfiddle.com/#!9/99d9360/3如果表只包含一条记录 - 请求不返回 –

+0

您的'WHERE'条件是时间<'2015-09-30'。在这种情况下,我的查询_应该不会返回任何记录。 –

+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

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