从sql server中的multivalue字段获取列名和值

时间:2017-02-12 04:28:22

标签: sql-server

我有这样的字段


D1=1.05,D2=1.05,D3=0.84,L1=1.12,L2=1.12,L3=1.12,L12=0.6,L22=0.6,L32=0.4800,I1=0.5,I2=0.5,I3=0.38,A=90,OF=-1

我怎么能让它看起来像这样


D1   D2    D3   L1   L2  L3   L12 L22 L32  I1  I2   I3  A  OF
1.05 1.05 0.84 1.12 1.12 1.12 0.6 0.6 0.48 0.5 0.5 0.38 90 -1

1 个答案:

答案 0 :(得分:2)

如果是值,您可以尝试:

DECLARE @s VARCHAR(max)='D1=1.05,D2=1.05,D3=0.84,L1=1.12,L2=1.12,L3=1.12,L12=0.6,L22=0.6,L32=0.4800,I1=0.5,I2=0.5,I3=0.38,A=90,OF=-1'
SET @s='select ['+REPLACE(REPLACE(@s,'=',']='),',',',[')
PRINT @s
EXEC(@s)
D1  D2  D3  L1  L2  L3  L12 L22 L32 I1  I2  I3  A   OF
1.05    1.05    0.84    1.12    1.12    1.12    0.6 0.6 0.4800  0.5 0.5 0.38    90  -1

使用拆分字符串和PIVOT

CREATE TABLE #tt(col varchar(max))
INSERT INTO #tt(col)VALUES('D1=1.05,D2=1.05,D3=0.84,L1=1.12,L2=1.12,L3=1.12,L12=0.6,L22=0.6,L32=0.4800,I1=0.5,I2=0.5,I3=0.38,A=90,OF=-1')

DECLARE @col VARCHAR(max),@sql VARCHAR(max)
IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t
SELECT y.* INTO #t FROM #tt AS t
CROSS APPLY(VALUES(CONVERT(XML,'<n><t>'+REPLACE(REPLACE(t.col,'=','</t><v>'),',','</v></n><n><t>')+'</v></n>'))) x(xcol)
CROSS APPLY(SELECT x.n.value('t[1]','varchar(200)') AS title, x.n.value('v[1]','varchar(200)') AS val FROM x.xcol.nodes('n') x(n)) y

SELECT @col=ISNULL(@col+',','')+QUOTENAME(title) FROM #t GROUP BY title
SET @sql='select * from #t pivot(max(val) for title in ('+@col+')) p'
PRINT @sql
EXEC(@sql)

处理多行: 如下面的样本数据,第2行有两个新列(B和D4)。

结果列列表组合了所有数据行的所有列。 它符合您的要求吗?

CREATE TABLE #tt(ID INT,col varchar(max))
INSERT INTO #tt(ID,col)VALUES(1,'D1=1.05,D2=1.05,D3=0.84,L1=1.12,L2=1.12,L3=1.12,L12=0.6,L22=0.6,L32=0.4800,I1=0.5,I2=0.5,I3=0.38,A=90,OF=-1')
                            ,(2,'D1=1.06,D2=1.06,D3=0.84,D4=1.84,L1=1.12,L2=1.12,L3=2.12,L12=0.6,L22=0.6,L32=0.5800,I1=0.5,I2=0.5,I3=1.38,A=90,B=99,OF=-1')


DECLARE @col VARCHAR(max),@sql VARCHAR(max)
IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t
SELECT ID, y.* INTO #t FROM #tt AS t
CROSS APPLY(VALUES(CONVERT(XML,'<n><t>'+REPLACE(REPLACE(t.col,'=','</t><v>'),',','</v></n><n><t>')+'</v></n>'))) x(xcol)
CROSS APPLY(SELECT x.n.value('t[1]','varchar(200)') AS title, x.n.value('v[1]','varchar(200)') AS val FROM x.xcol.nodes('n') x(n)) y

SELECT @col=ISNULL(@col+',','')+QUOTENAME(title) FROM #t GROUP BY title
SET @sql='select * from #t pivot(max(val) for title in ('+@col+')) p'
PRINT @sql
EXEC(@sql)
ID  A   B   D1  D2  D3  D4  I1  I2  I3  L1  L12 L2  L22 L3  L32 OF
1   90  NULL    1.05    1.05    0.84    NULL    0.5 0.5 0.38    1.12    0.6 1.12    0.6 1.12    0.4800  -1
2   90  99  1.06    1.06    0.84    1.84    0.5 0.5 1.38    1.12    0.6 1.12    0.6 2.12    0.5800  -1