declare @s nvarchar(4000),@i varchar(10)
select top 1
@i=count(*),
@s=''
from 人员表
group by 部门id
order by count(*) desc
while @i>0
select @s=',人员'+@i
+'=max(case when b.gid='+@i
+' then b.人员姓名 end)'+@s,
@i=@i-1
exec('
select a.部门名称,a.部门id'+@s+'
from 部门表 a,(
select 部门id,人员姓名,
gid=(select count(*) from 人员表 where 部门id=aa.部门id and 人员姓名<=aa.人员姓名)
from 人员表 aa
)b where a.部门id=b.部门id
group by a.部门名称,a.部门id')

解决方案 »

  1.   

    zjcxc大大 多谢回复,不过我试后好像不行。
    请再帮我看看好吗?
      

  2.   

    create table 部门表  (部门名称 nvarchar(100),部门ID int)
    create table 人员表  (部门ID int,人员名称  nvarchar(10)) insert into 部门表 select 'A',1 union all  select 'B',2 union all  select 'C',3 insert into 人员表 select 1,'King' union all  select 1,'Ralph' union all  select 1,'Terry'
    insert into 人员表 select 2,'King' union all  select 2,'Ralph'select * into #t from (select *,sid=(select count(*)+1 from 人员表 where 部门ID=a.部门ID and 人员名称<a.人员名称) from 人员表 a)T1declare @sql nvarchar(1000)
    set @sql='Select a.部门名称,a.部门ID '
    select @sql=@sql+',[人员'+cast(sid as nvarchar(10))+']=max(case when b.sid='+cast(sid as nvarchar(10))+' then b.人员名称 else '''' end)'
    from(
    select distinct sid from #t
    )T2select @sql=@sql+' from 部门表 a left join #t b on a.部门ID=b.部门ID group by a.部门名称,a.部门ID'print @sql
    exec(@sql)drop table #t,部门表,人员表
      

  3.   

    多谢xluzhong(Ralph),
    但是本人水平不高,能否添加一些注释。