简体   繁体   English

如何将月列和年列连接到年月列

[英]How can I concat month column and year column to yearmonth column

I have an SQL table with columns (month, year, and yearmonth)我有一个包含列(月、年和年月)的 SQL 表

Month    year    
 5       2020
 6       2020
 11      2020

I want to insert yearmonth column values in this format我想以这种格式插入 yearmonth 列值

yearmonth
   202005
   202006
   202011

I've tried couple of Datetime functions, but it didn't work.我尝试了几个 Datetime 函数,但没有用。

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.如果需要, lpad()将“缺少的” 0到月份部分,然后您可以将其与年份连接起来。

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)

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

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