问题
I have a date column like the next one stored as VARCHAR
(not DATE
type) and I want to convert it to an INTEGER
type with next format: YYYYMM
. So, for example, if this where my sample data:
period
"January 2018"
"February 2018"
"March 2018"
I would like to get the next integers:
result
201801
201802
201803
I have tried the next code:
select
period,
str_to_date(period, '%M %Y') as yearperiod
from
table
But this gives, for example, 2018-01-00
format which I would like to convert to the integer 201801
.
回答1:
You can do this with the next sequence of MySQL methods:
(1) First apply STR_TO_DATE(period, '%M %d %Y')
.
(2) Then apply DATE_FORMAT(<previous_result>, "%Y%m")
to the previous result.
(3) And finally use CONVERT(<previous_result>, UNSIGNED)
to do the integer cast over the previous result.
This is showed on the next example:
SELECT
period,
CONVERT(
DATE_FORMAT(
STR_TO_DATE(period, '%M %d %Y'),
"%Y%m"
),
UNSIGNED
) AS yearAndPeriod
FROM
<table_name>
Also, you can check it here:
DB Fiddle
来源:https://stackoverflow.com/questions/53656671/convert-column-with-month-name-and-year-to-integer-with-format-yyyymm-in-mysql