Warm tip: This article is reproduced from stackoverflow.com, please click
sql

SQL create extra column which gets data from the table two columns

发布于 2020-03-29 21:03:46

I have a query which have two fields that I would like to combine as a new column. On excel it goes something like this

=CONCATENATE([@CompanyID],[@Year],[@month])

But I don't know how to create this formula on sql that the output would be like

NEW ID = 88201911 aka 88=companyID 2019=year 11=month

Example code

Select 
companyID,
invoicedate,
month(invoicedate) as month,
year(invoicedate) as year,
concat('companyID','month','year')
 from accounting
Questioner
melx
Viewed
20
Gordon Linoff 2020-01-31 19:03

You cannot re-use a column alias in the same select. So you need to repeat the expressions:

month(invoicedate) as month,
year(invoicedate) as year,
concat(companyID, month(invoicedate), year(invoicedate))

In addition, never use single quotes to refer to columns. They should only be used for string and date constants.