2017-03-20 28 views
2
+-----+---------+--------+---------+ 
| 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 '減去'列金額的總金額WH列的金額有價值cr'。現在我怎麼把這個寫入一個查詢?mysql如何用2分不同,其中的條件在1個查詢

什麼我目前做的是使用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; 

我認爲必須有一種方式來獲得$總在不查詢兩次,但這樣我找不到任何鉛。

回答

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

你先生太棒了。非常感謝您提供非常簡單高效的查詢。 – Charas

0

像這樣的東西應該做的伎倆:

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()方法,並獲取列:

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

非常感謝您的回答。 :) – Charas

0

可以使用SQL查詢做「 sum_dr「和」sum_cr「。

+0

非常感謝您的回答。 – Charas

相關問題