+-----+---------+--------+---------+
| 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中的任何线索。
答案 0 :(得分:2)
SELECT
account,
SUM(CASE WHEN balance = 'dr' THEN amount
WHEN balance = 'cr' THEN -amount
ELSE 0
END
) amount
FROM
table
GROUP BY
account
答案 1 :(得分:1)
您可以使用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”。
答案 2 :(得分:0)
这样的事情可以解决问题:
SELECT SUM(IF(balance = 'dr', amount, (-1) * amount))
FROM table
WHERE account = 1
AND balance IN ('dr', 'cr')