我有3个表,如:
owner_details: -
owner_id owner_name
---------------------
1 A
2 B
3 C
-------------------
vehicle_owner: -
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)在表 交易 (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
-------------------
答案 0 :(得分:2)
答案 1 :(得分:0)
试试这个:
SELECT A.owner_id, A.owner_name, SUM(IFNULL(amount,0)) AMOUNT
FROM owner_details A LEFT JOIN
vehicle_owner B
ON A.owner_id=B.owner_id
LEFT JOIN `transaction` C
ON C.v_id=B.v_id
GROUP BY A.owner_id, A.owner_name;
答案 2 :(得分:0)
它对我有用
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 (SELECT v_id,
Coalesce(Sum(CASE
WHEN type = 0 THEN -amount
ELSE +amount
end), 0.0) AS amount
FROM `transaction`
GROUP BY v_id) t
ON vo.v_id = t.v_id
GROUP BY od.owner_id
感谢 Sebastian Brosch 快速回复!!!