我执行这个查询:
SELECT distinct(accounts.account_id), transactions.trn_code , transactions.trn_date
FROM accounts join transactions ON accounts.account_id = transactions.account_id
WHERE accounts.account_currency = 'USD' AND accounts.account_cards_linked > 1
AND transactions.trn_date >= '2015/03/01' AND transactions.trn_date <= '2015/03/31'
GROUP BY transactions.trn_code , transactions.trn_date,accounts.account_id
HAVING transactions.trn_date >= MAX(transactions.trn_date)
ORDER BY accounts.account_id;
我得到了这些结果: click image to see the result grid
我的问题是我希望每个帐户只显示最新日期的交易。但是现在如果一个账户有不止一笔交易,则全部出现。 (例如,我希望账户 912...129 在最近一天 2015/03/05 只出现一次。(示例参见图片)) 有什么想法吗??
最佳答案
您需要在每个帐户的 MAX(trn_date)
上执行 JOIN
:
SELECT
a.account_id,
t.trn_code,
t.trn_date
FROM accounts a
INNER JOIN transactions t
ON a.account_id = t.account_id
INNER JOIN (
SELECT
account_id, MAX(trn_date) AS trn_date
FROM transactions
WHERE
trn_date >= '2015/03/01'
AND trn_date <= '2015/03/31'
GROUP BY account_id
)td
ON t.account_id = td.account_id
AND t.trn_date = td.trn_date
WHERE
a.account_currency = 'USD'
AND a.account_cards_linked > 1
ORDER BY a.account_id
注意:使用有意义的表别名来提高可读性和可维护性。
关于mysql - 不能只显示多个交易的最大日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37176100/