简体   繁体   English

组合 MySQL 表中的 2 列以创建具有特定字符串的新列

[英]Combining 2 columns in MySQL table to create a new one with a specific string

I have the following columns in my table:我的表中有以下列:

launch_month    Years   
Jun             2018    
July            2018    
Aug             2018

I want to create a new column called 'launch_id' and combine the other 2 columns into a string of '201806', so the above would look like:我想创建一个名为“launch_id”的新列,并将其他 2 列组合成一个字符串“201806”,所以上面看起来像:

launch_month    Years   launch_id
Jun             2018    201806
July            2018    201807
Aug             2018    201808

Can anyone help?任何人都可以帮忙吗?

One option uses a case expression:一个选项使用case表达式:

select
    launch_month,
    years,
    years * 100 + case launch_month
        when 'Jan' then  1
        when 'Feb' then  2
        when 'Mar' then  3
        ...
        when 'Dec' then 12
    end launch_id
from mytable

This generates a new numeric column called launch_id , that represents the date in format YYYYMM .这会生成一个名为launch_id的新数字列,它表示格式YYYYMM的日期。

Alternatively, you can use date functions (but this might be less efficient):或者,您可以使用日期函数(但这可能效率较低):

select 
    launch_month,
    years,
    date_format(
        str_to_date(concat('01', launch_month, years), '%d%b%Y'),
        '%Y%m'
    ) launch_id
from mytable

This generates a string result.这会生成一个字符串结果。 If you want a number, you can just convert it, either explicitly ( cast() ) or implicitly ( + 0 ).如果你想要一个数字,你可以直接转换它,显式( cast() )或隐式( + 0 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM