首先是我的表格的一个例子:
id_object;time;value;status
1;2014-05-22 09:30:00;1234;1
1;2014-05-22 09:31:00;2341;2
1;2014-05-22 09:32:00;1234;1
...
1;2014-06-01 00:00:00;4321;1
...现在,我需要按月计算status=1和id_object=1的所有行。这是我的疑问:
SELECT COUNT(*)
FROM my_table
WHERE id_object=1
AND status=1
AND extract(YEAR FROM time)=2014
GROUP BY extract(MONTH FROM time)此示例的结果是:
2
15月份2次,6月份1次,但我需要一个全部12个月的产出,也是没有数据的月份。对于这个例子,我需要这个输出:
0 0 0 0 2 1 0 0 0 0 0 0寻求帮助。
发布于 2014-06-11 14:42:26
generate_series可以生成时间戳序列
select
g.month,
count(t)
from
generate_series(
(select date_trunc('year', min(t.time)) from t),
(select date_trunc('year', max(t.time)) + interval '11 months' from t),
interval '1 month'
) as g(month)
left outer join
t on
t.id_object = 1 and
t.status = 1 and
date_trunc('month', t.time) = g.month
where date_trunc('year', g.month) = '2014-01-01'::date
group by g.month
order by g.monthhttps://stackoverflow.com/questions/24156202
复制相似问题