Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get last 12 months data from Db with year in Postgres

Tags:

sql

postgresql

I want to fetch last 12 months data from db, I have written a query for that but that only giving me count and month but not year means month related to which year.

My 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)

it gives me output like this

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

but I want year with month like 7 - 2012, or year in other col, doesn't matter

like image 445
Inforian Avatar asked Sep 04 '13 06:09

Inforian


1 Answers

I believe you wanted this:

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
like image 108
mvp Avatar answered Oct 06 '22 09:10

mvp