Reputation: 2457
Have a table with a column like this:
first_day_month
01/07/2020
01/07/2020
01/08/2020
01/09/2020
.......
Need to create a column like year-month,
Tried to_char(first_day_month, 'MM/YYYY')
but got an error:
Error running query: INVALID_FUNCTION_ARGUMENT: Failed to tokenize string [M] at offset [0]
Tried
concat(extract(year from first_day_month),'-',extract(month from first_day_month) ) as month,
with an error:
Error running query: SYNTAX_ERROR: line 2:1: Unexpected parameters (bigint, varchar(1), bigint) for function concat. Expected: concat(array(E), E) E, concat(E, array(E)) E, concat(array(E)) E, concat(varchar)
Also tried date_parse but didn't get it right, any idea? Thanks
Upvotes: 0
Views: 582
Reputation: 65288
Your data doesn't seem to be of DATE
type, might be string, then need to convert to DATE
type first and format display style as desired pattern :
SELECT TO_CHAR(first_day_month::DATE,'MM/YYYY') AS first_day_month
FROM t
Upvotes: 0
Reputation: 521389
You need to use TO_DATE
first, to convert the column to a proper date. Then use TO_CHAR
to format as you want:
SELECT TO_CHAR(TO_DATE(first_day_month, 'DD/MM/YYYY'), 'MM/YYYY') AS my
FROM yourTable;
Note that in this case since the text month year you want is actually just the right substring, you could also directly use RIGHT
here:
SELECT RIGHT(first_day_month, 7)
FROM yourTable;
Finally, note that YYYY/MM
would generally be a better format to use, as it sorts properly. So perhaps consider using this version:
SELECT TO_CHAR(TO_DATE(first_day_month, 'DD/MM/YYYY'), 'YYYY/MM') AS ym
FROM yourTable;
Upvotes: 2