加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读