簡體   English   中英

在Postgres獲取Db的最近12個月的數據

[英]Get last 12 months data from Db with year in Postgres

我想從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的年份,並不重要

我相信你想要這個:

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
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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM