2016-05-11 62 views
0

我有這個疑問:每個帳戶誤差比較日期找出MAX(日)在MySQL

發現,他的最後一筆交易上,4月一個月,使用美元所有 賬戶。結果應鍵入:一)帳戶的 代碼 B)的最後一筆交易的代碼(如果有在一天內兩筆交易,你應該輸入脫穎而出 最新交易)的代碼) ç最後交易日期。

我的問題是這樣的:我如何比較一個帳戶的所有日期?

SELECT DISTINCT 
     accounts.account_id 
     ,transactions.trn_code 
     ,transactions.trn_date 
    FROM accounts 
     inner join transactions on accounts.account_id = transactions.account_id 
    WHERE 
     accounts.account_currency = 'DOL' 
     and transactions.trn_date = MAX(transactions.trn_date) 
     and transactions.trn_date >= 01/04/2016 and transactions.trn_date <= 31/4/2016 

這會導致錯誤(當然),因爲我不能使用MAX。但我認爲我必須爲每個帳戶的本月查找最大交易日期。這個想法是對的? 我該怎麼做?有任何想法嗎?

回答

1

你好你可以試試這個

SELECT accounts.account_id, transactions.trn_code , transactions.trn_date 
    FROM accounts inner join transactions on accounts.account_id = transactions.account_id 
    WHERE accounts.account_currency = 'DOL' 
and transactions.trn_date >= 01/04/2016 and transactions.trn_date <= 31/4/2016 and transactions.trn_date=(Select MAX(transactions.trn_date) from transactions) 
group by transactions.trn_code , transactions.trn_date,accounts.account_id 
+0

謝謝!它現在執行,但我沒有得到我想要的結果:/ 如果一個賬戶有一個以上的交易(在2016年1月1日 - 2016年4月31日之間),這些賬戶給了我這個賬戶的所有交易(每一個他的日期)。但我只希望帳戶的交易與最新的日期。 – Thodoris

+0

立即查看@Thodoris –