计算交易表中的余额,用户在此相互进行汇款

时间:2018-11-08 11:05:25

标签: mysql sql

我有一个这样设置的交易表:

-- Transactions table
+----+---------+-------+------------------+--------+-----------+
| id | from_id | to_id | transaction_type | amount | card_type |
+----+---------+-------+------------------+--------+-----------+
| 1  | 1       | 1     | deposit          | 90     | debit     |
| 2  | 1       | 2     | transfer         | -60    | debit     |
| 3  | 2       | 2     | deposit          | 10     | debit     |
| 4  | 2       | 2     | deposit          | 20     | credit    |
+----+---------+-------+------------------+--------+-----------+

如果我存入资金,它应该显示正值以表明已将钱添加到我的帐户中,但是如果我进行转帐,则应使用负余额来显示已从我的帐户中删除了钱。问题是,我想不出一个查询,该查询会将用户1的转帐中的钱添加到用户2的帐户中,以产生这样的视图(基于卡类型):

-- Debit Balance Table
+---------+---------+
| user_id | balance |
+---------+---------+
| 1       | 30      |
| 2       | 70      |
+---------+---------+

-- Credit Balance Table
+---------+---------+
| user_id | balance |
+---------+---------+
| 1       | 0       |
| 2       | 20      |
+---------+---------+

我知道您不能将钱添加到信用帐户中,但是暂时忘记这种逻辑。

1 个答案:

答案 0 :(得分:1)

对于debit,您可以简单地进行条件聚合:

SELECT 
  all_users.user_id, 
  SUM (CASE 
         WHEN t.transaction_type = 'deposit' AND all_users.user_id = t.from_id
           THEN ABS(t.amount) 
         WHEN t.transaction_type = 'transfer' AND all_users.user_id = t.from_id
           THEN -ABS(t.amount)
         WHEN t.transaction_type = 'transfer' AND all_users.user_id = t.to_id
           THEN ABS(t.amount)
         ELSE 0
       END
      ) AS balance 
FROM transactions AS t 
JOIN (
      SELECT from_id AS user_id FROM transactions 
      UNION 
      SELECT to_id FROM transactions
     ) AS all_users 
  ON t.from_id = all_users.user_id OR 
     t.to_id = all_users.user_id 
WHERE t.card_type = 'debit' 
GROUP BY all_users.user_id