我正在尝试在结果中创建一个新列,该列由“ PrimaryName”的前3个字符,所有“ VendorCity”和“ VendorZip”的前5个字符组成
SELECT,VendorName
,replace(PrimaryVendorLocationName,' ','') as PrimaryName
,replace(PrimaryVendorLocationCity,' ','') as VendorCity
,replace(PrimaryVendorLocationZipCode,' ','') as VendorZip
FROM [table]
如您所见,我还需要删除空格以确保更干净的返回。我想将新列称为“ NewVendorCode”。因此,记录是这样产生的:
R A Slack Chicago Heights 60654-1234
将返回此:
RASChicagoHeights60654
答案 0 :(得分:3)
您可以使用LEFT
(MySQL / TSQL)使用以下内容:
SELECT CONCAT(
LEFT(REPLACE(PrimaryVendorLocationName, ' ', ''), 3),
REPLACE(PrimaryVendorLocationCity, ' ', ''),
LEFT(REPLACE(PrimaryVendorLocationZipCode, ' ', ''), 5)
) FROM table_name
...或者您可以使用SUBSTRING
(MySQL / TSQL)(而不是LEFT
):
SELECT CONCAT(
SUBSTRING(REPLACE(PrimaryVendorLocationName, ' ', ''), 1, 3),
REPLACE(PrimaryVendorLocationCity, ' ', ''),
SUBSTRING(REPLACE(PrimaryVendorLocationZipCode, ' ', ''), 1, 5)
) FROM table_name
注意:如您所见,SELECT
查询可在MySQL和TSQL上正常运行。
演示(MySQL): https://www.db-fiddle.com/f/wTuKzosFgkEuKXtruCTCxg/0
演示(TSQL): http://sqlfiddle.com/#!18/dbc98/1/1
答案 1 :(得分:1)
您可以使用以下代码:
SELECT VendorName+
replace(PrimaryVendorLocationName,' ','') +
replace(PrimaryVendorLocationCity,' ','') +
replace(PrimaryVendorLocationZipCode,' ','') as NewVendorCode
答案 2 :(得分:0)
SELECT VendorName
,PrimaryName
,VendorCity
,VendorZip
,CONCAT(LEFT(PrimaryName,3),VendorCity,LEFT(VendorZip,5)) As NewVendorCode
FROM (
SELECT VendorName
,replace(PrimaryVendorLocationName,' ','') as PrimaryName
,replace(PrimaryVendorLocationCity,' ','') as VendorCity
,replace(PrimaryVendorLocationZipCode,' ','') as VendorZip
FROM [table]
)