Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

sql - Split the numeric string column in to multiple columns after each comma separated

split the string in multiple columns in a table for multiple columns. like i got this output from string aggregation I need to convert this in to three columns, length is not static since above numbers are coming based on calculation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In SQL Server 2016 you can use STRING_SPLIT to split the string (once you remove the surrounding ( and )) and then PIVOT that result to columns:

WITH CTE AS (
  SELECT value, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn
  FROM STRING_SPLIT(REPLACE(REPLACE('(0.0000, 3546.0000, 253422.000)', '(', ''), ')', ''), ',')
)
SELECT [1] AS Val1,
       [2] AS Val2,
       [3] AS Val3
FROM CTE
PIVOT (
  MAX(value)
  FOR rn IN ([1], [2], [3])
) p

Output:

Val1        Val2        Val3
0.0000      3546.0000   253422.000

Demo on dbfiddle

To do this with values in a table, you just need to CROSS APPLY the STRING_SPLIT to the table inside the CTE. For example, if the column is called exclusion in a table called data:

WITH CTE AS (
  SELECT exclusion, value, ROW_NUMBER() OVER (PARTITION BY exclusion ORDER BY (SELECT NULL)) AS rn
  FROM data
  CROSS APPLY STRING_SPLIT(exclusion, ',')
)
SELECT exclusion,
       [1] AS Val1,
       [2] AS Val2,
       [3] AS Val3
FROM CTE
PIVOT (
  MAX(value)
  FOR rn IN ([1], [2], [3])
) p

Demo on dbfiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...