如何在SQL中进行数据重组 - 从压缩到扩展

时间:2012-12-02 06:16:21

标签: sql sql-server sql-server-2008 tsql plsql

我有一个如下所示的订单表,其中与每个组关联的所有订单都列在同一个单元格中,但用逗号','分隔。现在我想扩展订单,以便每个订单的每个订单都放在不同的行中。 (结果表格低于原始表格。)

您能否告诉我如何在SQL中实现这一点?

非常感谢!

这是原始的紧凑表:

Group   Order
  1      ,a,b
  2      c,d,e
  3      f,g
  4      h

这是最终的扩展表:

Group  Order
  1     NULL
  1      a
  1      b
  2      c
  2      d
  2      e
  3      f
  3      g
  4      h

2 个答案:

答案 0 :(得分:0)

你可以做这样的事情,它对我很有用:

DECLARE @name_2 VARCHAR(MAX), @start INT, @flag bit, @id int ,@name nvarchar(max)

DECLARE c CURSOR LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR SELECT name,id FROM table_1;

open c;
FETCH NEXT FROM c INTO @name,@id;

WHILE @@FETCH_STATUS = 0
 BEGIN
   SET @flag = 1 
   SET @start = 0
   WHILE @start < LEN(@name) 
    BEGIN
      SET @start = @start + 1
      SET @name_2 =  SUBSTRING(@name, @start, 1) 
      if (@flag = 1 and @name_2 = ',')
          SET @name_2 = null 
      if(@name_2 <> ',' OR @name_2 is null)
        BEGIN   
           INSERT into dbo.Table_2 (id,name)
           values (@id,@name_2) 
        END
      SET @flag = 0   
    END
  FETCH NEXT FROM c INTO @name,@id;
END

CLOSE c;
DEALLOCATE c;

答案 1 :(得分:0)

你必须使用正则表达式,试试这个:

with temp  as (
     select 1 id, ',a,b' str from dual
     union all
     select 2, 'c,d,e' from dual
     union all
     select 3, 'f,g' from dual
     union all
     select 4, 'h' from dual    
)

SELECT distinct id, regexp_substr(str, '[^,]+', 1, level) str
FROM temp CONNECT BY instr(str, ',', 1, level - 1) > 0
order by 1, 2 nulls first