使用不同的分隔符将SQL中的值从一列拆分为多列

时间:2017-02-25 12:20:36

标签: sql-server

如何以任何可能的方式在SQL中执行此操作?

请参阅图片或以下内容:

||    Id    ||    Column1                      ||
||  1000    ||  SA(13), DS(1)                  ||
||  2000    ||  QW(1)                          ||
||  3000    ||  TE(23), RE(1), BB(40), VV(5)   ||

结果应该是:

|| Id   ||  Column2    ||  Colum3  ||
|| 1000 ||    SA       ||    13    ||
|| 1000 ||    DS       ||     1    ||
|| 2000 ||    QW       ||     1    ||
|| 3000 ||    TE       ||    23    ||
|| 3000 ||    RE       ||     1    ||
|| 3000 ||    BB       ||    40    ||
|| 3000 ||    VV       ||     5    ||

screenshot of the sample table

2 个答案:

答案 0 :(得分:2)

使用Jeff Moden的CSV分离器功能以及left()substring()

select 
    Id
 , col2 = left(x.Item,charindex('(',x.Item)-1)
 , col3 = substring(x.Item
          ,charindex('(',x.Item)+1
          ,charindex(')',x.Item)-charindex('(',x.Item)-1
          )
from t
  cross apply (
    select Item = ltrim(rtrim(i.Item))
      from [dbo].[delimitedsplit8K](t.col,',') as i
      ) x

返回:

测试设置:http://rextester.com/IOKB65736

+------+------+------+
|  Id  | col2 | col3 |
+------+------+------+
| 1000 | SA   |   13 |
| 1000 | DS   |    1 |
| 2000 | QW   |    1 |
| 3000 | TE   |   23 |
| 3000 | RE   |    1 |
| 3000 | BB   |   40 |
| 3000 | VV   |    5 |
+------+------+------+

拆分字符串参考:

答案 1 :(得分:1)

在SQL Server中执行此操作的一种方法是递归CTE:

with cte as (
      select id,
             left(column1, charindex(',', column1) - 1) as col23,
             substring(column1, charindex(',', column1) + 1) + ',' as rest
      from t
      union all
      select id,
             left(rest, charindex(',', rest) - 1) as col23
             substring(rest, charindex(',', rest) + 1) as rest
      from t
      where rest like '%,%'
     )
select id, left(col23, 2) as column2,
       replace(replace(substring(col23, 3, len(col23)), '(', ''), ')', '') as column3
from cte;

注意:这假设column2有两个字符(如示例数据中所示)。如果此情况有所不同,您还可以使用charindex()分割col23