我有兩個表1是帳戶,另一種是account_spend_history灰分帳戶是父/主表和噓一張小桌子。並與賬戶OneToMany有關係(賬戶表id是ash中的一個外鍵,如account_id)。請看圖片
現在我需要獲取account.id,總花費(這是amount_spend與相同的account_id的總和)和最後花費(是在灰表中插入的最後一條記錄,並且account_id即amount_spend值與MAX(ash.id))對應的,即
id | spend_total | last_spend --------------------------------- 1 | 30 | 18 2 | 280 | 120 3 | 20 | 20
SELECT a.id, SUM(ash.amount_spend) AS spend_total FROM accounts as a INNER JOIN account_spend_history AS ash ON ash.account_id = a.id GROUP BY a.id
即時得到ash.amount支出的account.id和總和,但我還需要最後的支出。如何獲得?
感謝。
謝謝@sgeddes,它正在爲我,我得到了期望的輸出。 –