微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

sqlserver多行转一行

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
*/

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐