Reputation: 1733
I have two column in sql
year month
2016 4
2014 5
What I want to do now is to combine these two columns together and get the period
Output
year month result
2016 4 201604
2014 5 201405
Are there ways to do this?
Upvotes: 1
Views: 1331
Reputation: 44696
If the column data types are integer, do
select year * 100 + month from tablename
Upvotes: 8
Reputation: 82474
Assuming both columns are numeric types:
SELECT year,
month,
CAST(year as char(4)) + RIGHT('00' + CAST(month as varchar(2)), 2) as result
FROM YourTable
Upvotes: 1
Reputation: 31879
First, you need to CAST
them to VARCHAR
to allow concatenation. Then use RIGHT
for month
to pad the value with 0
:
WITH Tbl AS(
SELECT 2016 AS [year], 4 AS [month] UNION ALL
SELECT 2014, 5
)
SELECT *,
CAST([year] AS VARCHAR(4)) + RIGHT('0' + CAST([month] AS VARCHAR(2)), 2)
FROM Tbl
Upvotes: 3