下表包含借记或贷记“操作”。我想从客户那里找到平衡:
CLIENT_ID | ACTION_TYPE | ACTION_AMOUNT
10 | credit | 100$
10 | debit | 62$
10 | credit | 62$
基于此代码:Using MySQL to calculate balances from debits and credits in a single table
SELECT client_id
, SUM(COALESCE(CASE WHEN action_type = 'debit' THEN action_amount END,0)) total_debits
, SUM(COALESCE(CASE WHEN action_type = 'credit' THEN action_amount END,0)) total_credits
, SUM(COALESCE(CASE WHEN action_type = 'debit' THEN action_amount END,0))
- SUM(COALESCE(CASE WHEN action_type = 'credit' THEN action_amount END,0)) balance
FROM my_table
WHERE CLIENT_ID = 10
GROUP
BY client_id
HAVING balance <> 0;
fowling代码给出了结果:Ballance -100,它是正确的但是在财务方面它是错的;
让我们分析一下行动:
1 -> customer gives payment in advance 100$ (credit)
2 -> customer invoice 62$ (debit)
3 -> customer pays invoice 62$ (credit)
4 -> ballance is -38$ not -100$
如何获得正确的Ballance,重新设计“Action”表或SQL代码?设置 - 信用没有帮助。
感谢您的帮助和时间。