将逗号分隔值拆分为多列
Split Comma Separated values into multiple column
我有一个要求,我的 SQL table 中有一列格式如下:
如何使用逗号分隔符拆分数据并将其插入到同一个新添加的列中table?
您的示例数据可能不需要任何拆分。您希望根据找到的值将数据移动到列中。您可以比拆分数据更简单地执行此操作。这适用于您的示例数据。
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
在我看来你需要使用 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
我有一个要求,我的 SQL table 中有一列格式如下:
如何使用逗号分隔符拆分数据并将其插入到同一个新添加的列中table?
您的示例数据可能不需要任何拆分。您希望根据找到的值将数据移动到列中。您可以比拆分数据更简单地执行此操作。这适用于您的示例数据。
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
在我看来你需要使用 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