sqlserver多行转一行
发布时间:2020-12-12 14:26:22 所属栏目:MsSql教程 来源:网络整理
导读:http://topic.csdn.net/u/20120705/11/e3c6d860-a46c-475c-808e-859475e9ad45.html?r=79037815-- 测试数据:[test] if object_id ( ' [test] ' ) is not null drop table [ test ] create table [ test ] ( [ Id ] int , [ 班级 ] int , [ 老师 ] varchar (
http://topic.csdn.net/u/20120705/11/e3c6d860-a46c-475c-808e-859475e9ad45.html?r=79037815 --> 测试数据:[test] if object_id('[test]') is not null drop table [test] create table [test]( [Id] int,[班级] int,[老师] varchar(2),[任职日期] datetime ) go insert [test] select 1,1,'张','2012-01-02' union all select 2,'李','2012-04-02' union all select 3,'王','2012-05-02' union all select 4,2,'刘','2012-02-02' union all select 5,'赵','2012-05-02' go declare @str varchar(2000) set @str='' select @str=@str+',[教师'+LTRIM(px)+']=max(case when px='+LTRIM(px) +' then [老师] else null end),[任职日期' +LTRIM(px)+']=max(case when px='+LTRIM(px)+' then convert(varchar(10),任职日期,120) else null end)' from ( select px=ROW_NUMBER()over(partition by [班级] order by id),* from test )t group by px exec('select [班级]'+@str+' from(select px=ROW_NUMBER()over(partition by [班级] order by id),* from test)t group by [班级]') /* 班级 教师1 任职日期1 教师2 任职日期2 教师3 任职日期3 1 张 2012-01-02 李 2012-04-02 王 2012-05-02 2 刘 2012-02-02 赵 2012-05-02 NULL NULL */ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |