【问题标题】:Calculate balances in transactions table where users send money to each other计算用户相互汇款的交易表中的余额
【发布时间】:2018-11-08 19:15:31
【问题描述】:

我有一个这样设置的事务表:

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

我知道您不能将钱添加到信用帐户,但现在忘记这个逻辑。

【问题讨论】:

    标签: mysql sql


    【解决方案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
    

    【讨论】:

    • @chinloyal 喜欢这个问题。有点棘手+1。希望你明白我想要做什么,否则我可以添加解释。
    • 我不是 sql 专家,但我明白你在做什么,这是一个非常好的解决方案。 @MadhurBhaiya
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 2013-05-26
    相关资源
    最近更新 更多