我正在尝试从 Mysql 数据库 中获取每个客户的最新交易,其中每个客户可能有不同数量的交易记录。
这里是Mysql表:
This table i have mentioned the rows which have bold (style), these bold rows are last transaction records.I want every customer last transaction.
我除了答案低于一。
我需要对这个选定的记录进行 mysql 查询。
最佳答案
您需要使用交易日期的 MAX
来查找最近的交易。由于这是一个聚合函数,您还需要 GROUP BY
您的 cus_id
。然后,此结果会为您提供客户的最新日期,这样您就可以根据该 cus_id
和 tranc_date
组合加入其余数据。
查询看起来像这样:
SELECT cus_tranc.cus_id,
cus_tranc.tranc_amt,
cus_tranc.tranc_type,
cus_tranc.tranc_date
FROM cus_tranc
INNER JOIN (
SELECT cus_id,
MAX(tranc_date) AS 'tranc_date'
FROM cus_tranc
GROUP BY cus_id) max_tranc ON cus_tranc.cus_id = max_tranc.cus_id AND cus_tranc.tranc_date = max_tranc.tranc_date
您可以在 this SQL Fiddle 中查看结果.
关于mysql - 我怎样才能在Mysql中获取每个客户的最后交易明细?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23782011/