0

I have a transaction table

I am able to get all the debit and credit transaction totals by property separately using these queries

SELECT property, SUM(amount) as creditamount FROM transactions WHERE transactions.type="CREDIT" GROUP BY property    

SELECT property, SUM(amount) as debitamount FROM transactions WHERE transactions.type="DEBIT" GROUP BY property

I am facing difficulty in having these two queries done in a single query so that i can subtract credit amount and debit amount for each row and list it according to the property

I tried using sub queries but multiple rows are returned.

Any way to achieve this?

Moishin
  • 59
  • 2
  • 12

2 Answers2

0

Use self join

select debitamount , creditamount
from (select sum(amount) income
     from  transactions 
     WHERE transactions.type="CREDIT"  
     GROUP BY property) i
JOIN (select sum(rate) debitamount 
     from transactions 
     WHERE transactions.type="DEBIT" 
     GROUP BY property) e

Refer this question

BhandariS
  • 606
  • 8
  • 20
0

Conditional aggregation may be what you are looking for.

SELECT property, 
 SUM(case when type = 'Credit' then amount else 0 end) as creditamount,
 SUM(case when type = 'Debit' then amount else 0 end) as debitamount,
 SUM(case when type = 'Credit' then amount else 0 end) -
 SUM(case when type = 'Debit' then amount else 0 end) as  diff
 FROM transactions 
 GROUP BY property 
P.Salmon
  • 17,104
  • 2
  • 12
  • 19