如何通过聚合对特定用户组合的值求和
How to sum values for specific user portfolios with aggregation
我有 3 个表和以下条目:
*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)
我需要创建一个查询来显示每个用户的总金额,其中连接的投资组合是“活跃的”。基本上,根据上面的插入,我应该:
name: 'jack', total_amount: 15
name: 'jill', total_amount: 3
我需要使用聚合吗?
查询应该是
SELECT u.name, SUM(d.amount) as total_amount FROM users u, deposits d, portfolios p
WHERE u.id=p.user_id and p.id=d.portfolio_id and p.status='active'
GROUP BY u.id
您应该加入,最好是显式加入,过滤 active
portfolio.status
在 users.name
上聚合并求和 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*/
我有 3 个表和以下条目:
*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)
我需要创建一个查询来显示每个用户的总金额,其中连接的投资组合是“活跃的”。基本上,根据上面的插入,我应该:
name: 'jack', total_amount: 15
name: 'jill', total_amount: 3
我需要使用聚合吗?
查询应该是
SELECT u.name, SUM(d.amount) as total_amount FROM users u, deposits d, portfolios p
WHERE u.id=p.user_id and p.id=d.portfolio_id and p.status='active'
GROUP BY u.id
您应该加入,最好是显式加入,过滤 active
portfolio.status
在 users.name
上聚合并求和 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*/