简体   繁体   中英

MySql how to select sum column with 2 different where conditions in 1 query

+-----+---------+--------+---------+
| 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.

SELECT
   account,
   SUM(CASE WHEN balance = 'dr' THEN amount
      WHEN balance = 'cr' THEN -amount
      ELSE 0
      END
   ) amount
FROM
   table
GROUP BY
   account

You can do it using SQL query:

SELECT 
    SUM(CASE WHEN balance = 'dr' THEN amount ELSE NULL END) AS sum_dr,
    SUM(CASE WHEN balance = 'cr' THEN amount ELSE NULL END) AS sum_cr
FROM table
WHERE account = 1
AND balance IN ('dr', 'cr')

Put the query above to the CI query() method and fetch columns: "sum_dr" and "sum_cr" from the result array.

Something like this should do the trick:

SELECT SUM(IF(balance = 'dr', amount, (-1) * amount))
FROM table
WHERE account = 1
AND balance IN ('dr', 'cr')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM