[英]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 |
+-----+---------+--------+---------+
我有上面的示例表,我正在使用CI,我想选择“列值WHERE列余额具有值dr”的总和减去“列值WHERE列余额具有值cr”的总和。 现在如何将其写到一个查询中?
我目前正在使用2个查询,如下所示
// 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;
我认为必须有一种方法来获得$ total而不查询两次,但是我找不到SO的线索。
SELECT
account,
SUM(CASE WHEN balance = 'dr' THEN amount
WHEN balance = 'cr' THEN -amount
ELSE 0
END
) amount
FROM
table
GROUP BY
account
您可以使用SQL查询来做到这一点:
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')
将上面的查询放入CI query()方法并从结果数组中获取列:“ sum_dr”和“ sum_cr”。
这样的事情应该可以解决问题:
SELECT SUM(IF(balance = 'dr', amount, (-1) * amount))
FROM table
WHERE account = 1
AND balance IN ('dr', 'cr')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.