Postgresql组明智地使用缺少的值 [英] Postgresql group month wise with missing values
本文介绍了Postgresql组明智地使用缺少的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
首先是我的表的示例:
first an example of my table:
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个月的所有行。这是我的查询:
Now i need count all rows with status=1 and id_object=1 monthwise for example. this is my query:
SELECT COUNT(*)
FROM my_table
WHERE id_object=1
AND status=1
AND extract(YEAR FROM time)=2014
GROUP BY extract(MONTH FROM time)
这个例子的结果是:
The result for this example is:
2
1
2代表may和1代表6月份,但是我需要12个月的输出,还有没有数据的月份。对于这个例子,我需要这个输出:
2 for may and 1 for june but i need a output with all 12 months, also months with no data. for this example i need this ouput:
0 0 0 0 2 1 0 0 0 0 0 0
Thx for help。
Thx for help.
推荐答案
<您可以使用 generate_series()
函数如下所示:
you can use generate_series()
function like this:
select
g.month,
count(m)
from generate_series(1, 12) as g(month)
left outer join my_table as m on
m.id_object = 1 and
m.status = 1 and
extract(year from m.time) = 2014 and
extract(month from m.time) = g.month
group by g.month
order by g.month
这篇关于Postgresql组明智地使用缺少的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文