sql 多行、一行 互转

原始数据:

sql 多行、一行 互转

期望数据:

sql 多行、一行 互转

 IF OBJECT_ID('temp_20170701','u') IS NOT NULL DROP TABLE temp_20170701

  CREATE TABLE temp_20170701 (
ID INT PRIMARY KEY IDENTITY(1,1),
NAME NVARCHAR(50),
Subjectname NVARCHAR(50),
Score INT
)
 INSERT dbo.temp_20170701( Name, subjectname, Score )
SELECT 'A','语文','' UNION
SELECT 'A','数学','' UNION
SELECT 'A','英语','' UNION
SELECT 'B','语文','' UNION
SELECT 'B','数学','' UNION
SELECT 'B','英语','' UNION
SELECT 'C','语文','' UNION
SELECT 'C','数学','' UNION
SELECT 'C','英语','' UNION
SELECT 'D','英语',''
 SELECT Name ,Score=STUFF((SELECT ','+CONVERT(NVARCHAR(max),Score) FROM temp_20170701 t1 WHERE t1.NAME=t2.NAME FOR XML PATH('')),1,1,'')
FROM temp_20170701 t2 GROUP BY t2.NAME
 

原始数据:

sql 多行、一行 互转

期望数据:

sql 多行、一行 互转

 CREATE TABLE temp_20170702 (
ID INT PRIMARY KEY IDENTITY(1,1),
NAME NVARCHAR(50),
Score varchar(100)
)
 insert temp_20170702 (Name,Score)
select 'A','30,40,20' union
select 'B','60,70,50' union
select 'C','90,100,80' union
select 'D',''
 select a.NAME,b.value as Score from (
select *,s=CONVERT(xml,'<root><v>'+REPLACE(Score,',','</v><v>')+'</v></root>') from temp_20170702
) a outer apply
(select value=n.s.value('.','varchar(100)') from a.s.nodes('/root/v') n(s)) b
上一篇:Sql:多行合并一行以及多条数据取时间最早的那条


下一篇:(转)SQL查询案例:多行转换为一行