我需要输出以下情况:
+-----------------+--------+
| STRING in table | OUTPUT |
+-----------------+--------+
| NONGL_NONGL | NONGL |
| GL252_GL252 | GL |
| GL400_GL400 | GL |
| NOS_NOS | NOS |
+-----------------+--------+
我尝试使用SUBSTRING()
,但它没有给我正确的输出。
答案 0 :(得分:0)
这应该做你想要的:
select (case when col like 'NONGL%' then 'NONGL'
when col like 'GL%' then 'GL'
when col like 'NOS%' then 'NOS'
end) as new_col
答案 1 :(得分:0)
这是另一种方式:
DECLARE @StrTable Table (Str VARCHAR(MAX) );
INSERT INTO @StrTable VALUES
('NONGL_NONGL'),
('GL252_GL252'),
('GL400_GL400'),
('NOS_NOS');
SELECT Str,
IIF(Str LIKE 'NONGL%','NONGL',IIF(Str LIKE 'GL%', 'GL', IIF(Str LIKE 'NOS%', 'NOS', Str))) AS Outputs
FROM @StrTable;
结果:
+-------------+---------+
| Str | Outputs |
+-------------+---------+
| NONGL_NONGL | NONGL |
| GL252_GL252 | GL |
| GL400_GL400 | GL |
| NOS_NOS | NOS |
+-------------+---------+
答案 2 :(得分:0)
因此,您需要NONGL
和NOS
结果:
SELECT LEFT([col_name], CHARINDEX('_', [col_name]) - 1)
对于GL
输出,由于字符串包含您需要的数字PATINDEX()
:
SELECT LEFT([col_name], PATINDEX('%[0-9]%', [col_name]) - 1)
最后只需使用CASE WHEN
DECLARE @tbl Table (string VARCHAR(MAX) );
INSERT INTO @tbl VALUES
('NONGL_NONGL'),
('GL252_GL252'),
('GL400_GL400'),
('NOS_NOS');
SELECT
string
,CASE WHEN
string LIKE '%[0-9]%' then LEFT(string, PATINDEX('%[0-9]%', string) - 1)
ELSE LEFT(string, CHARINDEX('_', string) - 1)
END AS [Output]
from @tbl