2013-05-01 188 views
0

我有一个包含多个事务的表。我正在尝试获取最后一笔交易的记录。 我使用了以下内容:在mysql中选择最大记录数

select n.AccountNumber, max(PostDate), f.TransAmt 
from mp_cycle n, fintrans f 
where n.AccountNumber = f.AccountNumber 
and TransCode >= '50' 
and TransCode <= '59' 
group by n.AccountNumber 

这是返回的最后日期为特定帐户,但TransAmt是不相同的记录。

即:

Acct # Date Amt 
1  1/1 10.00 
1  1/2 11.00 
1  1/3 12.00 
2  1/2 20.00 
2  1/3 21.00 
2  1/4 22.00 

我的选择将返回的最后日期为每个帐户,所以对于1/3的行为#1和1/4的行为#2,但金额字段不是AMT是与该记录一致。

任何援助将不胜感激。

回答

1

有很多方法可以解决这个问题,一个是通过加入额外的子查询,每个AccountNumber分别得到最新的PostDate。子查询的结果将在另一个表上进行连接,前提是它应该匹配两列:AccountNumberPostDate

SELECT a.*, b.* 
FROM mp_cycle a 
     INNER JOIN fintrans b 
      ON a.AccountNumber = b.AccountNumber 
     INNER JOIN 
     (
      SELECT AccountNumber, MAX(PostDate) max_date 
      FROM fintrans 
      GROUP BY AccountNumber 
     ) c ON b.AccountNumber = c.AccountNumber AND 
       b.PostDate = c.max_date 
-- WHERE ..your conditions here.. 
+0

我修改了顶部的选择,只选择我需要的3个字段,并在指定的位置添加了where子句。这似乎运作良好。谢谢! – 2013-05-01 16:19:54