我有 3 个表,例如:
所有者详细信息:-
owner_id owner_name
---------------------
1 A
2 B
3 C
-------------------
车辆所有者:-
v_id vehicle_id owner_id
-------------------------
1 1 1
2 2 2
3 4 1
4 3 1
5 5 3
交易:-
id v_id amount transaction_type
--------------------------------
1 1 100 0
2 2 250 1
3 1 150 1
4 3 450 1
5 1 200 0
6 4 300 1
7 5 150 0
8 5 200 1
transaction_type= 0 然后 (-) transaction_type=1 然后 (+)
车主 A (1) 在表 vehicle_owner 中有 3 辆带有 v_id (1,3,4) 的车辆。
v_id (1,3,4) 在表 transaction (1,3,4,5,6) 中有 5 个条目金额总和600(-100+150+450-200+300)
现在我想要这样的列表:-.
owner_id owner_name amount
---------------------
1 A 600
2 B 250
3 C 50
-------------------
最佳答案
您可以使用以下查询:
SELECT od.owner_id, od.owner_name, SUM(t.amount) AS amount
FROM owner_details od INNER JOIN vehicle_owner vo ON od.owner_id = vo.owner_id
INNER JOIN `transaction` t ON vo.v_id = t.v_id
GROUP BY od.owner_id
<小时/>
如果您想使用额外的transaction_type
,您可以使用以下内容:
SELECT od.owner_id, od.owner_name, SUM(CASE WHEN t.transaction_type = 0 THEN t.amount * -1 ELSE t.amount END) AS amount
FROM owner_details od INNER JOIN vehicle_owner vo ON od.owner_id = vo.owner_id
INNER JOIN `transaction` t ON vo.v_id = t.v_id
GROUP BY od.owner_id
关于mysql - 如何获取通过加入返回的多个帐户的金额总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48744642/