日期:2014-05-18  浏览次数:20548 次

sqlserver查询多行并一行
Id 班级 老师 任职日期
1 1 张 2012-01-02
2 1 李 2012-04-02
3 1 王 2012-05-02
4 2 刘 2012-02-02
5 2 赵 2012-05-02
------------------------
如上结果集,我想查出的结果为这样:
班级 老师 任职日期 老师 任职日期 老师 任职日期
1 张 2012-01-02 李 2012-04-02 王 2012-05-02
2 刘 2012-02-02 赵 2012-05-02 NULL NULL
------------------------
其中每种班级的行数不确定,以最多行数的班级为准,不够的为NULL
比如班级1有3行,班级2有2行,则以班级1为准。(其中每种班级的行数不确定)

相当于纵向变横向排列了,而且按日期先后。请问怎么做。

------解决方案--------------------
SQL code
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([Id] int,[班级] int,[老师] varchar(2),[任职日期] datetime)
insert [tb]
select 1,1,'张','2012-01-02' union all
select 2,1,'李','2012-04-02' union all
select 3,1,'王','2012-05-02' union all
select 4,2,'刘','2012-02-02' union all
select 5,2,'赵','2012-05-02'
go

declare @sql varchar(8000)
select 
  @sql=isnull(@sql+',','')
  +'max(case when rn='+ltrim(rn)+' then 老师 end) as [老师'+ltrim(rn)+'],'
  +'max(case when rn='+ltrim(rn)+' then convert(varchar(10),任职日期,120) end) as [任职日期'+ltrim(rn)+']'
from( 
select distinct rn=(select count(1) from tb where 班级=t.班级  and id<=t.id) from tb t
) t2

exec ('select 班级,'+@sql+' from ('
  +'select *,rn=(select count(1) from tb where 班级=t.班级 and id<=t.id) from tb t) t2'
  +' 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

(2 行受影响)
**/

------解决方案--------------------
SQL code

--> 测试数据:[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,1,'李','2012-04-02' union all
select 3,1,'王','2012-05-02' union all
select 4,2,'刘','2012-02-02' union all
select 5,2,'赵','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
*/