3
MONTHNAME我有一個表,它看起來像:組由SQL
id | Item | Quantity | Amount | created
________________________________________________
1 | Monitor | 10 | 5000 | 2013-01-11
2 | Keyboard| 10 | 200 | 2013-02-19
3 | Monitor | 10 | 5000 | 2013-02-13
3 | Keybard | 10 | 200 | 2013-04-19
當我通過查詢:
SELECT monthname(created) AS
MONTH , sum(quantity) AS qty
FROM `sales`
WHERE year(created) = '2013'
GROUP BY monthname(created)
ORDER BY monthname(created) DESC
它給出結果:
month | qty
______________________
January | 10
February | 20
April | 10
但什麼我試圖檢索的是:
month | qty
______________________
January | 10
February | 20
March | 0
April | 10
- 因爲我沒有銷售沒有長征的結果必須返回3月營收與數量0
我在我的應用程序中使用笨,所以如果我們無法通過SQL解決它,然後可能是你能證明我通過Codeigniter解決它的方法。
$this->db->select('monthname(created) as month, sum(quantity) as qty'); $this->db->from('sales'); $this->db->where('year(created) = 2013'); $this->db->group_by('monthname(created)'); $this->db->order_by('monthname(created)'); $this->data['sales'] = $this->db->get()-result();
在視圖:
輸出$data
的
$data = array();
foreach($sales as $sale) {
$data[] = $sale->qty;
}
:
10, 20, 10 in array;
我需要的是
10, 20, 0, 10 array
檢查這裏http://stackoverflow.com/questions/17916322/mysql-to-select-month-wise-record-even-if-data-not-exist –
或這裏http://stackoverflow.com/questions/11516688/sql-to-select-one-record-for-every-month-with-a-sum-of-that-months-records –