SQL将表多行整成一行的问题
新手问个问题:
情景是这样的,比如我有张表,里面放的信息是 :name,score,testNo,就是说,记录了比如:
张三 90 1,
张三 59 2,
张三 39 3,
就是什么人第几次考试分数是多少。然后我在存储过程里面,要转化成 name,test1,test2,test3,比如转化成:
张三 90,59 ,39
就是表多行转化到表的一行里面去。不知道我表述清不清楚?
请教各位了。
[解决办法]
--> 测试数据:[test]if object_id('[test]') is not null drop table [test]create table [test]([name] varchar(4),[score] int,[test] int)insert [test]select '张三',90,1 union allselect '张三',59,2 union allselect '张三',39,3declare @str varchar(max)set @str=''select @str=@str+','+'[test'+LTRIM(test)+']=max(case when [test]='+ltrim(test)+ ' then score else 0 end)' from test group by testexec('select name'+@str+' from test group by name')/*name test1 test2 test3张三 90 59 39*/
[解决办法]
结果用一个字段可行?
declare @t table ([name] varchar(20),score int,testNo int)insert into @tselect '张三',90, 1 union allselect '张三',59, 2 union allselect '张三',39, 3 union allselect '李四',75, 1select [name]+ (select ','+cast(score as varchar(20)) from @t as X where X.[name]=Y.[name] order by testNo for xml path('')) as test from @t as Ygroup by [name]/*(2 行受影响)test---------------李四,75张三,90,59,39*/