我有一张桌子:
member [member_id,member_name]
我的另一张桌子是:
balance [balance_id,member_id,balance(transaction)]
现在我已加入这些表并为member_id相同的位置添加SUM(余额)! 示例:
构件:
member_id , member_name
1, test_1
2, test_2
平衡
balance_id,member_id,balance
1,1,-800
2,1,1000
3,2,500
会员加入余额
member_id , balance
1,200
2,500
注意:我通过一个查询完成了所有这些操作!
答案 0 :(得分:0)
对于您的预期输出,这将执行:
select member_id,
sum(balance) balance
from balance
group by member_id
如果您需要将其与成员表一起加入,请执行:
select m.*,
b.balance
from member m
join (
select member_id,
sum(balance) balance
from balance
group by member_id
) b on m.member_id = b.member_id;
另一种方法是先加入然后进行聚合:
select m.member_id,
m.member_name,
sum(b.balance) balance
from member m
join balance b on m.member_id = b.member_id
group by m.member_id,
m.member_name;