2013-04-04 40 views
1

我有一个问题 - 我需要从列Column3(分隔符'|')分隔数据。如何从一列中分离多个数据?

Column1 Column2 Column3 
7  23  567|568|85|532|296|581|300|265|577|330|563|423|55|442 
8   0  242 
9   0  242 
10  23  567|568|85|532|296|581|300|265|577|330|563|423|55|442 
14  4  330|563|423|134|242 

Column1是ID,Column2是'|'为每一行计数,第3列是应该在新行中分开的数据。

我的输出应该是这样的:

Column1 Column4 
7  567 
8  242 
9  242 
10  567 
14  330 
7  568 
10  568 
14  563 

我写了工会象下面,但我不想重复它的60倍......

select 
    Column1, 
    substring_index(substring_index(Column2,'|',1),'|',-1) as Column2 
from Table1 
union 
select 
    Column1, 
    substring_index(substring_index(Column2,'|',2),'|',-1) as Column2 
from Table1 

你能帮我找到一个解决方案更好

BR

+0

只是一个建议,但不能在编程上更容易(即调用你的数据库的程序,如C#服务器等等)而不是数据库? – 2013-04-04 19:25:01

+0

就我而言,从应用程序发送一列中的这些数据更容易(这只是操作日志表的一小部分)。但谢谢你的建议! – 2013-04-04 19:41:47

回答

2

你可以用数字列表来做到这一点。这里是一个例子:

select Column1, 
     substring_index(substring_index(Column2,'|', nums.n),'|',-1) as Column2 
from Table1 t1 cross join 
     (select (n1.n - 1) * 12 + (n2.n - 1)*3 + n3.n as n 
     from (select 1 as n union all select 2 union all select 3 union all select 4 union all select 5 
      ) n1 cross join 
      (select 1 as n union all select 2 union all select 3 union all select 4 
      ) n2 cross join 
      (select 1 as n union all select 2 union all select 3 
      ) n3 
    ) nums 
+0

谢谢@Gordon Linoff!它的工作原理就是我期望的!这真的很聪明(和简单)的想法。谢谢。我试图用count列,但没有成功。你的想法更好。 – 2013-04-04 19:46:48

相关问题