我有一張桌子,如下圖所示。如何SELECT SUM列價格WHERE type = 1 AND type = 2?我只需要一個查詢中type = 1的價格總數和type = 2的價格總數。如何在1個SQL查詢中的2個條件下獲得2個總和?
+-----+------+-------+
| PID | Type | Price |
+-----+------+-------+
| 1 | 1 | 100 |
| 2 | 2 | 65 |
| 3 | 1 | 300 |
| 4 | 1 | 200 |
| 5 | 2 | 50 |
+-----+------+-------+
我都試過,但它返回一個錯誤:
$this->db->select("SUM(price) as total1, (SELECT SUM(price) where type=2) as total2");
$this->db->from('table');
$this->db->where('type', '1');
$query = $this->db->get();
$result = $query->result();
我也試着寫我的查詢,但無濟於事一些其他的方式,和所有其他方面,我在SO是發現對於我的簡單查詢來說太複雜了。我認爲這應該是一個非常簡單的查詢。
當前查詢的結果是什麼? –
這個查詢返回正確的計算'選擇SUM(價格)作爲total1,(選擇SUM(價格)從堆棧where類型= 2)作爲total2從堆棧where type = 1' –
@RahulSharma它返回錯誤「您在您的錯誤SQL語法「 – Charas