根据条件在sql中拆分逗号分隔值

时间:2017-05-20 13:06:53

标签: sql sql-server sql-server-2012

大家好我是SQL新手我有一个表,其中有一个名为dilution_name的列,在这一列中有值以逗号分隔格式,如A,B,C等。这些值可能会像某些行一样变化值是A,B,C,在某些情况下,它像A,B,C,D我只想分隔这些值并在多列中打印它们如果只有3个逗号分隔值那么在逗号中应该有3个值会写的休息应该是null 我试过了

    select ParsedData.* 
    from dilution_table mt
    cross apply ( select str = mt.dilution_name + ',,' ) f1
    cross apply ( select p1 = charindex( ',', str ) ) ap1
    cross apply ( select p2 = charindex( ',', str, p1 + 1 ) ) ap2
    cross apply ( select p3 = charindex( ',', str, p2 + 2 ) ) ap3
    cross apply ( select p4 = charindex( ',', str, p3 + 3 ) ) ap4
    cross apply ( select p5 = charindex( ',', str, p4 + 4 ) ) ap5
    cross apply ( select p6 = charindex( ',', str, p5 + 5 ) ) ap6
    cross apply ( select val1 = substring( str, 1, p1-1 )                   
             , val2 = substring( str, p1+1, p2-p1-1 ),
              val3 = substring( str, p2+1, p2-p1-1 ),
              val4 = substring( str, p3+1, p2-p1-1 ),
              val5 = substring( str, p4+1, p2-p1-1 ),
              val6 = substring( str, p5+1, p2-p1-1 ),
              val7 = substring( str, p6+1, p2-p1-1 )
      ) ParsedData  


            [sample data][1]

sample data

1 个答案:

答案 0 :(得分:0)

在SQL Server 2016+中,您可以使用string_split()(尽管它没有序号)。

在2016年之前的SQL Server中,使用Jeff Moden的CSV Splitter表值函数:

declare @str varchar(128) = 'a,b,c,d'

select s.ItemNumber, s.Item
from dbo.delimitedsplit8k(@str,',') s;

rextester演示:http://rextester.com/EGZ24917

返回:

+------------+------+
| ItemNumber | Item |
+------------+------+
|          1 | a    |
|          2 | b    |
|          3 | c    |
|          4 | d    |
+------------+------+

要在拆分后转动数据,您可以使用条件聚合,如下所示:

select 
    v1 = max(case when s.ItemNumber = 1 then s.Item end)
  , v2 = max(case when s.ItemNumber = 2 then s.Item end)
  , v3 = max(case when s.ItemNumber = 3 then s.Item end)
  , v4 = max(case when s.ItemNumber = 4 then s.Item end)
  , v5 = max(case when s.ItemNumber = 5 then s.Item end)
from dbo.delimitedsplit8k(@str,',') s;

返回:

+----+----+----+----+------+
| v1 | v2 | v3 | v4 |  v5  |
+----+----+----+----+------+
| a  | b  | c  | d  | NULL |
+----+----+----+----+------+

拆分字符串参考: