日期:2014-05-18 浏览次数:20523 次
--> 测试数据:[test] if object_id('[test]') is not null drop table [test] create table [test]( [studentId] varchar(1), [subject] varchar(4), [point] int, [classOrder] int, [gradeOrder] int ) insert [test] select 'A','语文',90,1,2 union all select 'A','数学',80,4,15 union all select 'A','英语',95,2,4 union all select 'B','语文',85,6,25 union all select 'B','数学',98,1,2 union all select 'B','英语',100,1,1 declare @str varchar(max) set @str='' select @str=@str+','+[subject]+'=max(case when [subject]='+QUOTENAME([subject],'''') +' then [point] else 0 end),' +'classOrder'+'=max(case when [subject]='+QUOTENAME([subject],'''') +' then [classOrder] else 0 end),' +'gradeOrder'+'=max(case when [subject]='+QUOTENAME([subject],'''') +' then [gradeOrder] else 0 end)' from test group by [subject] exec('select [studentId]'+@str+' from test group by [studentId]') /* studentId 数学 classOrder gradeOrder 英语 classOrder gradeOrder 语文 classOrder gradeOrder ------------------------------------------- A 80 4 15 95 2 4 90 1 2 B 98 1 2 100 1 1 85 6 25 */
------解决方案--------------------