根据您的问题,这只是 4 列的示例。这可以概括为:
with cte as(
SELECT id,CHARINDEX(',', value) First_occurence,
CHARINDEX(',', value, CHARINDEX(',', value)+1) Second_occurrence,
CHARINDEX(',', value, CHARINDEX(',', value, CHARINDEX(',', value)+1)+1) Third_occurrence
from test)
select substring(value,1,first_occurence-1) col1,
substring(value,first_occurence+1,Second_occurrence-(first_occurence+1)) col2,
substring(value,Second_occurrence+1,Third_occurrence-(Second_occurrence+1)) col3,
substring(value,Third_occurrence+1,len(value)) col4
from test a
inner join
cte b
on a.id=b.id
广义:
Declare @col_count int=1
;with cte as(
SELECT id, @col_count col,value,CHARINDEX(',', value) occurence,substring(value,1,CHARINDEX(',', value)-1) col_val from test
union all
select id, col+1 col,value, CHARINDEX(',', value, occurence+1),
substring(value,occurence+1,CHARINDEX(',', value, occurence+1)-(occurence+1))
from cte
where (occurence+1)< len(value)
union all
select id, col+1 col,value, occurence+1,
substring(value,occurence+1,len(value))
from cte
where (occurence+1)= len(value)
)
SELECT [1], [2], [3], [4]
from
(
SELECT col, col_val,
row_number() over(partition by col order by col_val) rn
from cte
) as st
pivot
(
max(col_val)
FOR col in ([1], [2], [3], [4])
) as pivottable
只需添加 [5] ,[6],.... 即可在 final 中添加更多列select
。
SQL小提琴