Convert column with Month Name and Year to integer with format YYYYMM in MySQL

守給你的承諾、 提交于 2021-01-29 02:35:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!