Skip to content
Advertisement

Order By Month Name – Postgresql

I followed this post Order by using month name in PostgreSQL but not success!

I have a query (its working) and I just need to order the results by mont name. This is thr query I am using:

   select to_char(purchase_date, 'Month') as mes_2021,
           sum(gmv::float4) as soma_gmv
           from tablename
    where purchase_date > '2021-01-01'
    GROUP BY mes_2021

I am trying:

order by to_date(purchase_date, 'Month') - No success
order by date_part(purchase_date::date, 'Month') - No success

If i use order by mes_2021

enter image description here

Advertisement

Answer

One trick is to use a window function on the date:

select to_char(purchase_date, 'Month') as mes_2021,
       sum(gmv::float4) as soma_gmv
from tablename
where purchase_date > '2021-01-01'
group by mes_2021
order by min(purchase_date);

This, of course, assumes that the dates are all in the same year. But your where clause is taking care of that.

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