+-----+---------+--------+---------+
| PID | account | amount | balance |
+-----+---------+--------+---------+
| 1 | 1 | 100 | dr |
| 2 | 5 | 100 | cr |
| 3 | 2 | 30 | dr |
| 4 | 1 | 30 | cr |
| 5 | 1 | 50 | cr |
| 6 | 4 | 50 | dr |
+-----+---------+--------+---------+
I have the sample table above, I am using CI and I want to select sum the total amount of 'column amount WHERE column balance has value dr' minus total amount of 'column amount WHERE column balance has value cr'. Now how do I write this into just one query ??
What I'm currently doing is using 2 queries such as below
// Get total amount that has balance dr of account 1
$this->db->select_sum('amount');
$query = $this->db->get_where('table', array('account' => '1', 'balance' => 'dr');
$result = $query->result();
$total_dr = $result[0] -> amount;
// Get total amount that has balance cr of account 1
$this->db->select_sum('amount');
$query = $this->db->get_where('table', array('account' => '1', 'balance' => 'cr');
$result = $query->result();
$total_cr = $result[0] -> amount;
// Minus total_dr to total_cr
$total = $total_dr - $total_cr;
I think there must be a way to get $total without querying twice, but I couldn't find any lead in SO.