sql 多行一行 互转
Posted 真的勇士,敢于直面惨淡的warning、敢于正视淋漓的err
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 多行一行 互转相关的知识,希望对你有一定的参考价值。
原始数据:
期望数据:
1 IF OBJECT_ID(\'temp_20170701\',\'u\') IS NOT NULL DROP TABLE temp_20170701 2 3 CREATE TABLE temp_20170701 ( 4 ID INT PRIMARY KEY IDENTITY(1,1), 5 NAME NVARCHAR(50), 6 Subjectname NVARCHAR(50), 7 Score INT 8 )
1 INSERT dbo.temp_20170701( Name, subjectname, Score ) 2 SELECT \'A\',\'语文\',\'20\' UNION 3 SELECT \'A\',\'数学\',\'30\' UNION 4 SELECT \'A\',\'英语\',\'40\' UNION 5 SELECT \'B\',\'语文\',\'50\' UNION 6 SELECT \'B\',\'数学\',\'60\' UNION 7 SELECT \'B\',\'英语\',\'70\' UNION 8 SELECT \'C\',\'语文\',\'80\' UNION 9 SELECT \'C\',\'数学\',\'90\' UNION 10 SELECT \'C\',\'英语\',\'100\' UNION 11 SELECT \'D\',\'英语\',\'100\'
1 SELECT Name ,Score=STUFF((SELECT \',\'+CONVERT(NVARCHAR(max),Score) FROM temp_20170701 t1 WHERE t1.NAME=t2.NAME FOR XML PATH(\'\')),1,1,\'\') 2 FROM temp_20170701 t2 GROUP BY t2.NAME
原始数据:
期望数据:
1 CREATE TABLE temp_20170702 ( 2 ID INT PRIMARY KEY IDENTITY(1,1), 3 NAME NVARCHAR(50), 4 Score varchar(100) 5 )
1 insert temp_20170702 (Name,Score) 2 select \'A\',\'30,40,20\' union 3 select \'B\',\'60,70,50\' union 4 select \'C\',\'90,100,80\' union 5 select \'D\',\'100\'
1 select a.NAME,b.value as Score from ( 2 select *,s=CONVERT(xml,\'<root><v>\'+REPLACE(Score,\',\',\'</v><v>\')+\'</v></root>\') from temp_20170702 3 ) a outer apply 4 (select value=n.s.value(\'.\',\'varchar(100)\') from a.s.nodes(\'/root/v\') n(s)) b
以上是关于sql 多行一行 互转的主要内容,如果未能解决你的问题,请参考以下文章