2014-01-11 29 views
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 
+0

檢查這裏http://stackoverflow.com/questions/17916322/mysql-to-select-month-wise-record-even-if-data-not-exist –

+0

或這裏http://stackoverflow.com/questions/11516688/sql-to-select-one-record-for-every-month-with-a-sum-of-that-months-records –

回答

0

我認爲最好的辦法是有一個月表看起來如下

id | Month 
--------------------- 
1 | January 
2 | February 
3 | March 
4 | April 
5 | May 
6 | June 
7 | July 
8 | August 
9 | September 
10 | October 
11 | November 
12 | December 

名此表作爲

,你可以使用查詢,如下

SELECT 
    months.`month`, 
    Sum(sales.quantity) 
FROM 
    sales 
RIGHT OUTER JOIN months ON months.`month` = monthname(sales.created) 
GROUP BY 
    months.`month` 
ORDER BY 
    months.id 

這應該工作得很好!

這裏是SQL Fiddle,這將有助於你