【问题标题】:SQL, get adhering pairs of values from comma separated stringSQL,从逗号分隔的字符串中获取遵循的值对
【发布时间】:2014-04-03 14:06:05
【问题描述】:

我在一列的一个单元格中有以下字符串(示例):

 1,4,3,8,23,7

我需要将如下的值对放入一个新表中:

(1,4)
  (4,3)
    (3,8)
      (8,23)
        (23,7)

我希望我正确地解释了我需要什么,以便您能够理解我:) 我很欣赏一个句子的答案,因为我喜欢自己解决编程问题:)

【问题讨论】:

    标签: sql sql-server regex string


    【解决方案1】:
    DECLARE @data varchar(2000) = '1,4,3,8,23,7'
    
    ;WITH x as
    (
         SELECT t.c.value('.', 'VARCHAR(2000)') v, row_number() over (order by (select 1)) rn
          FROM (
             SELECT x = CAST('<t>' + 
                   REPLACE(@data, ',', '</t><t>') + '</t>' AS XML)
         ) a
         CROSS APPLY x.nodes('/t') t(c)
    )
    SELECT t1.v, t2.v
    FROM x t1
    JOIN x t2
    on t1.rn = t2.rn - 1
    

    结果:

    1   4
    4   3
    3   8
    8   23
    23  7
    

    【讨论】:

      【解决方案2】:

      很抱歉破坏了乐趣:)

      declare 
          @col_list varchar(1000),
          @sep char(1)
      
      set @col_list = '1,4,3,8,23,7'
      set @sep = ','
      
      ;with x as (
      select substring(@col_list, n, charindex(@sep, @col_list + @sep, n) - n) as col,
      row_number() over(order by n) as r
      from numbers where substring(@sep + @col_list, n, 1) = @sep
      and n < len(@col_list) + 1
      )
      select x2.col, x1.col
      from x as x1
      inner join x as x2 on x1.r = x2.r+1
      

      http://dataeducation.com/you-require-a-numbers-table/

      【讨论】:

        【解决方案3】:

        另一种不使用 XML 的解决方案 - 使用递归 CTE 的基于清晰集合的方法。

        create table #tmp (value varchar(100));
        insert into #tmp values ('1,4,3,8,23,7');
        
        
        with r as (
            select value, cast(null as varchar(100)) [x], 0 [no] from #tmp
            union all
            select right(value, len(value)-case charindex(',', value) when 0 then len(value) else charindex(',', value) end) [value]
            , left(r.[value], case charindex(',', r.value) when 0 then len(r.value) else abs(charindex(',', r.[value])-1) end ) [x]
            , [no] + 1 [no]
            from r where value > '')
        
        select '(' + cast(s1.[x] as varchar(10)) +', '+ cast(s2.[x] as varchar(10)) + ')'
        from r as s1
        join r as s2 on s1.[no] + 1 = s2.[no]
        where s1.x is not null;
        
        
        drop table #tmp;
        

        输出:

        result
        ---------
        (1, 4)
        (4, 3)
        (3, 8)
        (8, 23)
        (23, 7)
        

        【讨论】:

          猜你喜欢
          • 2019-05-08
          • 2011-09-07
          • 1970-01-01
          • 2017-07-22
          • 1970-01-01
          • 1970-01-01
          • 2014-03-22
          • 2017-08-04
          • 1970-01-01
          相关资源
          最近更新 更多