2013-04-04 45 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

相關問題