Skip to content
Advertisement

Group query results by month and year in postgresql

I have the following database table on a Postgres server:

id      date          Product Sales
1245    01/04/2013    Toys    1000     
1245    01/04/2013    Toys    2000
1231    01/02/2013    Bicycle 50000
456461  01/01/2014    Bananas 4546

I would like to create a query that gives the SUM of the Sales column and groups the results by month and year as follows:

Apr    2013    3000     Toys
Feb    2013    50000    Bicycle
Jan    2014    4546     Bananas

Is there a simple way to do that?

Advertisement

Answer

select to_char(date,'Mon') as mon,
       extract(year from date) as yyyy,
       sum("Sales") as "Sales"
from yourtable
group by 1,2

At the request of Radu, I will explain that query:

to_char(date,'Mon') as mon, : converts the “date” attribute into the defined format of the short form of month.

extract(year from date) as yyyy : Postgresql’s “extract” function is used to extract the YYYY year from the “date” attribute.

sum("Sales") as "Sales" : The SUM() function adds up all the “Sales” values, and supplies a case-sensitive alias, with the case sensitivity maintained by using double-quotes.

group by 1,2 : The GROUP BY function must contain all columns from the SELECT list that are not part of the aggregate (aka, all columns not inside SUM/AVG/MIN/MAX etc functions). This tells the query that the SUM() should be applied for each unique combination of columns, which in this case are the month and year columns. The “1,2” part is a shorthand instead of using the column aliases, though it is probably best to use the full “to_char(…)” and “extract(…)” expressions for readability.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement