答案 0 :(得分:3)
您的样本数据可能不需要任何拆分。您想根据其找到的值将数据移动到列。您可以比拆分数据简单一些。这对您的样本数据来说很好。
declare @Something table
(
Combined_Column varchar(10)
)
insert @Something values
('1,2,3')
, ('2')
, ('1,3')
, ('1,2,3,4')
, ('1,3,4')
, ('1')
, ('4')
select *
, col1 = case when charindex('1', s.Combined_Column) > 0 then 1 end
, col2 = case when charindex('2', s.Combined_Column) > 0 then 2 end
, col3 = case when charindex('3', s.Combined_Column) > 0 then 3 end
, col4 = case when charindex('4', s.Combined_Column) > 0 then 4 end
from @Something s
答案 1 :(得分:2)
在我看来,您需要使用CASE WHEN END
来实现它。
select value, case when CHARINDEX('1', value) > 0 then '1' else '' end col1,
case when CHARINDEX('2', value) > 0 then '2' else '' end col2,
case when CHARINDEX('3', value) > 0 then '3' else '' end col3,
case when CHARINDEX('4', value) > 0 then '4' else '' end col4
from #a
输出
已更新 Demo
如果值可能为('11,2,3')
,则应使用如下所示的STRING_SPLIT
来获得准确的结果。
select value,
case when EXISTS(SELECT TOP 1 1 FROM STRING_SPLIT(value, ',') s where s.value = '1') then '1' else '' end col1,
case when EXISTS(SELECT TOP 1 1 FROM STRING_SPLIT(value, ',') s where s.value = '2') then '2' else '' end col2,
case when EXISTS(SELECT TOP 1 1 FROM STRING_SPLIT(value, ',') s where s.value = '3') then '3' else '' end col3,
case when EXISTS(SELECT TOP 1 1 FROM STRING_SPLIT(value, ',') s where s.value = '4') then '4' else '' end col4
from #a