0

My data is stored in mysql.

My Table data is as follows

3   credit  500.00
3   debit   500.00
4   credit  300.00
4   debit   300.00
5   credit  300.00
5   debit   300.00
6   credit  300.00
6   debit   300.00

I want to write a query to write data as customer id, credit, debit,final_amount

where as final amount = credit-debit

Can someone please help me with query?

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
Thoughtful Monkey
  • 648
  • 2
  • 10
  • 24

1 Answers1

2

You can use conditional aggregation:

select customerid, 
       sum(case when type = 'credit' then amount else 0 end) as credit,
       sum(case when type = 'debit' then amount else 0 end) as debit,
       sum(case when type = 'credit' then amount
                when type = 'debit' then - amount
                else 0
           end) as credit
from t
group by customerid;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786