SQL选择MySQL上帐户的最后一条记录

时间:2017-06-01 14:35:13

标签: mysql sql greatest-n-per-group

我有如下表格

id transaction    value  date       account number
1                 5      05/01/17   AA1
2                 3      05/02/17   AA2
3                 7      05/01/17   AA3
4                 3      05/03/17   AA2
5                 5      05/02/17   AA1
6                 3      05/02/17   AA5
7                 5      05/03/17   AA1
8                 3      05/04/17   AA2
9                 5      05/04/17   AA1
10                3      05/02/17   AA4
11                5      05/05/17   AA1
12                3      05/06/17   AA2
13                5      05/05/17   AA1
14                3      05/07/17   AA2
15                5      05/07/17   AA1
16                5      05/01/17   AA6
17                3      05/08/17   AA2

我想为每个帐户选择最后一笔交易记录

5 个答案:

答案 0 :(得分:1)

您需要按帐号分组。见下文

CREATE TABLE #t (id int, value  DECIMAL(18,2), date DATETIME, account_number VARCHAR(50))

SELECT  T1.*
FROM    #T T1
       INNER JOIN (  SELECT account_number, MAX(id) id
                     FROM  #T 
                     GROUP BY account_number  ) T2
               ON T2.account_number = T1.account_number
               AND T2.id = T1.id

答案 1 :(得分:0)

SELECT fields FROM table ORDER BY id DESC LIMIT 1;

答案 2 :(得分:0)

试试这个:

SELECT TOP 1 * FROM Table ORDER BY DESC

答案 3 :(得分:0)

如果你的数据库是有序的(我假设这个)试试这个

SELECT * FROM  TABLE WHERE ID = (SELECT MAX(ID)  FROM TABLE)

答案 4 :(得分:0)

试一试。

select t1.*
from table_name as t1,
(select account_number, max(id) as id from table_name group by account_number) as t2
where t1.id = t2.id;