在用户相互汇款的事务表中计算余额

62lalag4  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(228)

我有一个如下设置的事务表:

-- 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      |
+---------+---------+

我知道你不能把钱加到信用账户上,但现在就忘了这个逻辑。

uyhoqukh

uyhoqukh1#

为了 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

相关问题