Mysql
 sql >> Database >  >> RDS >> Mysql

Utilizzo di MySQL per calcolare saldi da debiti e crediti in un'unica tabella

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(transaction_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,client_id INT NOT NULL
,action_type VARCHAR(12) NOT NULL
,action_amount INT NOT NULL
);

INSERT INTO my_table(client_id,action_type,action_amount) VALUES
(1            ,'debit',         1000),
(1            ,'credit',         100),
(1            ,'credit',         500),
(2            ,'debit',          1000),
(2            ,'credit',         1200),
(3            ,'debit',          1000),
(3            ,'credit',         1000),
(4            ,'debit',          1000);


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 
 GROUP  
    BY client_id
HAVING balance <> 0;


+-----------+--------------+---------------+---------+
| client_id | total_debits | total_credits | balance |
+-----------+--------------+---------------+---------+
|         1 |         1000 |           600 |     400 |
|         2 |         1000 |          1200 |    -200 |
|         4 |         1000 |             0 |    1000 |
+-----------+--------------+---------------+---------+