select transferTypes from TransferData
transferTypes
--------------
TTH, TT
TRANSIT, TTH
ST, TRANSIT
TRANSIT, TTH
ST, TT
有什么方法或内置功能可以达到以下效果?
尝试使用以下
IN
条件,但无法获得所需的结果。预期结果:
select transferTypes from TransferData where transferTypes in ('TT, ST')
transferTypes
-------------
TTH, TT
ST, TRANSIT
ST, TT
select transferTypes from TransferData where transferTypes in ('TTH, TRANSIT')
transferTypes
-------------
TTH, TT
TRANSIT, TTH
ST, TRANSIT
TRANSIT, TTH
select transferTypes from TransferData where transferTypes in ('TT')
transferTypes
-------------
TTH, TT
ST, TT
最佳答案
首先,您需要将列表(以斜线表示)转换为以逗号开头和结尾且不包含空格的形式。然后,您可以结合使用charindex
和or
运算符来检查特定值还是包含在记录中:
declare @TransferData table (transferTypes varchar(20));
insert into @TransferData values
('TTH, TT'),
('TRANSIT, TTH'),
('ST, TRANSIT'),
('TRANSIT, TTH'),
('ST, TT');
select * from (
select ',' + replace(transferTypes, ' ', '') + ',' transferTypes from @TransferData
) a
where charindex(',TT,', transferTypes) > 0
or charindex(',ST,', transferTypes) > 0
关于sql-server - SQL IN条件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56107403/