Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sum values for specific user portfolios with aggregation

I have 3 tables and followinn entries:

*users [id, name]*
insert into users (1, 'jack')

*portfolios [id, user_id, status]*
insert into portfolios (1, 1, 'active')
insert into portfolios (2, 1, 'active')

*deposits [id, portfolio_id, amount]*
insert into deposits (1, 1, 10)
insert into deposits (2, 2, 5)

*users [id, name]*
insert into users (2, 'jill')

*portfolios [id, user_id, status]*
insert into portfolios (3, 2, 'active')
insert into portfolios (4, 2, 'pending')

insert into deposits (3, 3, 3)
insert into deposits (4, 4, 4)

I need to create a query that will show the total amount for each user, where the connected portoflio is "active. Basically, according to inserts above, I should have:

name: 'jack', total_amount: 15
name: 'jill', total_amount: 3

Do I need to use aggregation?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should join, preferably with explicit joins, filter for active portfolio.status aggregate on users.name and sum deposits.amount

select 
users.name, sum(deposits.amount) as total_amount /*each distinct user and the sum for their amount*/
from users
inner join  portfolio on users.id = portfolio.user_id  /*use explicit joins on corresponding ids*/
inner join  deposits on portfolio.id = deposits.portfolio_id
where portfolio.status = 'active' /*filter for active only*/
group by users.name  /*this gives unique list of users*/
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading