在Postgres获取Db的最近12个月的数据

时间:2013-09-04 06:45:13

标签: sql postgresql

我想从db中获取最近12个月的数据,我已经为此编写了一个查询,但只给了我数月和月而不是年份意味着与哪一年相关的月份。

我的Sql:

Select count(B.id),date_part('month',revision_timestamp) from package AS
 A INNER JOIN  package_revision AS B ON A.revision_id=B.revision_id 
 WHERE  revision_timestamp > (current_date - INTERVAL '12 months') 
GROUP BY  date_part('month',revision_timestamp)

它给我这样的输出

 month | count 
-------+-------
     7 |     21
     8 |      4
     9 |     10

但是我想要像2012年7月一样的月份,或者在其他col的年份,并不重要

2 个答案:

答案 0 :(得分:10)

我相信你想要这个:

SELECT to_char(revision_timestamp, 'YYYY-MM'),
       count(b.id)
FROM package a
JOIN package_revision b ON a.revision_id = b.revision_id
WHERE revision_timestamp >
      date_trunc('month', CURRENT_DATE) - INTERVAL '1 year'
GROUP BY 1

答案 1 :(得分:4)

select
    count(B.id),
    date_part('year', revision_timestamp) as year,
    date_part('month',revision_timestamp) as month
from package as A
    inner join package_revision as B on A.revision_id=B.revision_id 
where
    revision_timestamp > (current_date - INTERVAL '12 months') 
group by
    date_part('year', revision_timestamp)
    date_part('month', revision_timestamp)

select
    count(B.id),
    to_char(revision_timestamp, 'YYYY-MM') as month
from package as A
    inner join package_revision as B on A.revision_id=B.revision_id 
where
    revision_timestamp > (current_date - INTERVAL '12 months') 
group by
    to_char(revision_timestamp, 'YYYY-MM')

请注意,如果您按revision_timestamp > (current_date - INTERVAL '12 months')进行过滤,则会获得去年当前日期的范围(因此,如果今天为'2013-09-04',您将获得'2012-09-04'的范围)