2017-02-25 369 views
1

如何以任何可能的方式在SQL中執行此操作?使用不同的分隔符將SQL中一列中的值拆分爲多列

請參閱圖像或以下:

|| Id || Column1      || 
|| 1000 || SA(13), DS(1)     || 
|| 2000 || QW(1)       || 
|| 3000 || TE(23), RE(1), BB(40), VV(5) || 

的結果應該是:

|| Id || Column2 || Colum3 || 
|| 1000 || SA  || 13 || 
|| 1000 || DS  ||  1 || 
|| 2000 || QW  ||  1 || 
|| 3000 || TE  || 23 || 
|| 3000 || RE  ||  1 || 
|| 3000 || BB  || 40 || 
|| 3000 || VV  ||  5 || 

screenshot of the sample table

+3

這顯示了一個非常貧窮的數據庫設計:( – Khan

回答

1

一種方式在SQL Server做,這是一個遞歸CTE:

with cte as (
     select id, 
      left(column1, charindex(',', column1) - 1) as col23, 
      substring(column1, charindex(',', column1) + 1) + ',' as rest 
     from t 
     union all 
     select id, 
      left(rest, charindex(',', rest) - 1) as col23 
      substring(rest, charindex(',', rest) + 1) as rest 
     from t 
     where rest like '%,%' 
    ) 
select id, left(col23, 2) as column2, 
     replace(replace(substring(col23, 3, len(col23)), '(', ''), ')', '') as column3 
from cte; 

注意:這假定column2有兩個字符(如您的示例數據)。如果這可能會有所不同,您還可以使用charindex()拆分col23

+0

我得到這個錯誤 「通過向左或子功能無效的長度參數」 –

+0

@drummerboi這裏是一個基於戈登的答案的工作版本:http://rextester.com/NDQ10805 – SqlZim

+0

@SqlZim - 非常感謝你,它的工作....... !!!!!!!! Yeeeeeeey! –

2

使用由傑夫MODEN一個CSV分路器功能與left()substring()沿:

select 
    Id 
, col2 = left(x.Item,charindex('(',x.Item)-1) 
, col3 = substring(x.Item 
      ,charindex('(',x.Item)+1 
      ,charindex(')',x.Item)-charindex('(',x.Item)-1 
     ) 
from t 
    cross apply (
    select Item = ltrim(rtrim(i.Item)) 
     from [dbo].[delimitedsplit8K](t.col,',') as i 
    ) x 

回報:

測試設置:http://rextester.com/IOKB65736

+------+------+------+ 
| Id | col2 | col3 | 
+------+------+------+ 
| 1000 | SA | 13 | 
| 1000 | DS | 1 | 
| 2000 | QW | 1 | 
| 3000 | TE | 23 | 
| 3000 | RE | 1 | 
| 3000 | BB | 40 | 
| 3000 | VV | 5 | 
+------+------+------+ 

分割字符串參考:

+0

這些鏈接很棒! – ATC

+0

有沒有一個查詢,不需要一個函數,我沒有一個函數訪問我們的數據庫中運行 –

+0

@drummerboi [Gordon Linoff的答案](http://stackoverflow.com/a/42456086/2333499)不需要一個功能。 – SqlZim