2013-12-22 36 views
0

我在數據庫(源碼)表中顯示爲 「0」 .The表有兩列:如何,當我在SQL查詢中使用GROUP BY

samochod_id samochod_data_dodania  
1   2012-11-13 
2   2012-12-18 
3   2012-12-21 
4   2013-01-03 
5   2013-02-16 
6   2013-02-27 
7   2013-04-03 

我使用的查詢:

select  strftime('%Y',samochod_data_dodania) as year, 
      strftime('%m',samochod_data_dodania) as month,    
      count() ile 
from samochod 
where samochod_data_dodania between '2012-09-11' and '2013-05-26' 
group by year,month 

結果:

year month ile 
2012 11  1 
2012 12  2 
2013 01  1 
2013 02  2 
2013 04  1 

我想:

year month ile 
2012 09  0 
2012 10  0 
2012 11  1 
2012 12  2 
2013 01  1 
2013 02  2 
2013 03  0 
2013 04  1 
2013 05  0 

怎麼辦呢?請幫助:)

回答

1

你想要的條件進入聚集和出where條款:

select strftime('%Y',samochod_data_dodania) as year, 
     strftime('%m',samochod_data_dodania) as month,    
     sum(case when samochod_data_dodania between '2012-09-11' and '2013-05-26' then 1 else 0 
      end) as ile 
from samochod 
group by year, month; 

這是假設你有每個月至少一個記錄。如果沒有,那麼你需要一個左外連接:

select year, month, count(*) as ile 
from (select '2012' as year, '09' as month union all 
     select '2012', '10' union all 
     select '2012', '11' union all 
     select '2012', '12' union all 
     select '2013', '01' union all 
     select '2013', '02' union all 
     select '2013', '03' union all 
     select '2013', '04' union all 
     select '2013', '05' 
    ) ym left outer join 
    samochod 
    on ym.year = strftime('%Y', samochod_data_dodania) and 
     ym.month = strftime('%m', samochod_data_dodania) 
group by ym.year, ym.month; 
0

我不知道你的情況,但你可以測試以下方法:

  1. 插入數據後,在表中可以排序有柱,下方條款。

ORDER BY column1 DESC,column2。

我希望這會有所幫助。