i have 2 table 1 account , other 1 account_spend_history ash account parent/master table , shin sub table. , has relationship onetomany account(account table id foreign key in ash account_id). please see image
now need account.id, total spend (which sum of amount_spend same account_id) , last spend (is last record inserted in ash table against , account_id i.e. amount_spend value corresponding max(ash.id)), is
id | spend_total | last_spend --------------------------------- 1 | 30 | 18 2 | 280 | 120 3 | 20 | 20
select a.id, sum(ash.amount_spend) spend_total accounts inner join account_spend_history ash on ash.account_id = a.id group a.id
im getting account.id , sum of ash.amount spend, need last spend. how that?
thanks.
here's 1 option using correlated subquery
:
select a.id, sum(ash.amount_spend) spend_total, (select amount_spend account_spend_history ash2 ash2.account_id = a.id order ash2.id desc limit 1) last_spend accounts inner join account_spend_history ash on ash.account_id = a.id group a.id
Comments
Post a Comment