我在数据库(sqlite)中有表。该表有两列:
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
怎么做?请帮助:)
答案 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;
答案 1 :(得分:0)
我不确定你的情况,但你可以测试以下方法:
ORDER BY column1 DESC,column2。
我希望它会有所帮助。