I have a table like this in my database

now what I want is to extract the sum of **credit** where **credit_type** equals **V** and sum of **credit** where **credit_type** equals **R**, then find the difference between the two(R and V). My result should contain **identity_number**, **sum of credit where credit_type equals V**, **sum of credit where credit_type equals R**, **balance between the two sums**. As an example looking at the above table identity_number 2885 should have something like this in my returned result **2885, 3000, 1560+370, 3000-(1560+370)**. How do I write such a query? hope you understood the problem.

## Best Answer

You may use

`SUM`

function with`IF`

to choose what to take into consideration for each row. Here is my example: