Question

I am trying to format a Vertica date column into only the month.

I would need the final value in some sort of date datatype so in the report I can order the results by date/time, not order by text. So that February sorts after January etc.

select TO_DATE(TO_CHAR(purchase_date), 'Month')  
from transactions
order by 1;

I am also tried:

select TO_DATE(TO_CHAR(MONTH(purchase_date)), 'Month')  
from transactions
order by 1;

The above statements produce an error "Invalid value for Month"

Any ideas?

Was it helpful?

Solution

How about this?

select to_char(purchase_date, 'Month')
from transactions
order by purchase_date;

You can order by columns that are not in the select list.

EDIT:

If you want to combine months from multiple years, the above will not work quite right. This will:

select to_char(purchase_date, 'Month')
from transactions
order by extract(month from purchase_date);

OTHER TIPS

Select TO_CHAR((NOW() - INTERVALYM '1 MONTH'), 'MON');

Output:

JUN

This will help you get only the name of the previous month.

We can directly use date_part to get a month from the timestamp.

SELECT DATE_PART('MONTH', purchase_date) purchase_date

TO_DATE gives the complete date, if you only provide MM in the parameter then Vertica set default year and day.

Let suppose the month number is 8.

SELECT TO_DATE(purchase_date, 'MM')

Output: (0001-08-01)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top