我有表users
,deposits
和withdrawals
,我正在尝试编写查询以获取用户 balance 。
desposits
id | amount | user_id
1 | 4000 | 1
2 | 3500 | 1
withdrawals
id | amount | user_id
1 | 4000 | 1
这是我当前的查询:
SELECT u.id AS user_id,
COALESCE(SUM(d.amount), 0) AS sum_deposits,
COALESCE(SUM(w.amount), 0) AS sum_withdrawals
FROM users AS u
WHERE u.id = 1
LEFT JOIN deposits AS d ON u.id = d.user_id
LEFT JOIN withdrawals AS w ON u.id = w.user_id
GROUP BY u.id
我得到的结果是-500,我认为这是因为提款计算了两次,例如:SUM(4000, 3500) - SUM(4000, 4000) = -500
如何解决我的查询?
答案 0 :(得分:2)
您应该使用子查询
SELECT u.id AS user_id,
(SELECT COALESCE(SUM(d.amount), 0)
FROM deposits AS d WHERE u.id = d.user_id) AS sum_deposits,
(SELECT COALESCE(SUM(w.amount), 0)
FROM withdrawals AS w WHERE u.id = w.user_id) AS sum_withdrawals
FROM users AS u
WHERE u.id = 1
答案 1 :(得分:1)
我会union all
而不是加入:
select user_id,
sum(case when trans_type = 'Deposit' then amount end) as sum_deposit,
sum(case when trans_type = 'Withdrawal' then amount *-1 end) as sum_Withdrawal,
sum(amount) as net_amount
from
(
select user_id, amount, 'Deposit' as trans_type
from Deposits
union all
select user_id, amount * -1, 'Withdrawal'
from Withdrawals
) t1
group by user_id
答案 2 :(得分:0)
试试这个-
SELECT A.user_id, A.amount - B.amount Balance
FROM (
SELECT user_id,SUM(amount) amount
FROM desposits
GROUP BY user_id
) A
LEFT JOIN (
SELECT user_id,SUM(amount) amount
FROM withdrawals
GROUP BY user_id
)B ON A.User_id = B.user_id