简体   繁体   中英

How can I concat month column and year column to yearmonth column

I have an SQL table with columns (month, year, and yearmonth)

Month    year    
 5       2020
 6       2020
 11      2020

I want to insert yearmonth column values in this format

yearmonth
   202005
   202006
   202011

I've tried couple of Datetime functions, but it didn't work.

I think that it is simpler to use string functions:

select t.*, concat(year, lpad(month, 2, '0')) as yearmonth
from mytable t

lpad() adds the "missing" 0 to the month part if needed, which you can then concatenate with the year.

On the other hand, if you want a numeric result, arithmetics is the way to go:

select t.*, year * 100 + month as yearmonth
from mytable t

如果你想要一个字符串,我可能会使用:

select cast(year * 100 + month as char)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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