[英]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.