将逗号分隔的值拆分为多列

时间:2020-02-17 15:27:13

标签: sql sql-server ssis

我有一个要求,我的SQL表中必须有以下格式的列:

SQL Column

如何使用逗号分隔符拆分数据并将其插入同一表中新添加的列中?

enter image description here

2 个答案:

答案 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)

Demo on db<>fiddle

在我看来,您需要使用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

输出

enter image description here

已更新 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

enter image description here