declare @s nvarchar(4000)
set @s=''
select @s=@s+','+quotename(编号)
+'=isnull(max(case 编号 when '+rtrim(编号)
+' then 值 end),'''')'
from A
group by 编号
exec('select 类型'+@s+' from A group by 类型')

解决方案 »

  1.   

    --测试--测试数据
    create table A(类型 varchar(10),编号 int,值 varchar(10))
    insert A  select 'A',1,'a'
    union all select 'A',2,'b'
    union all select 'A',3,'c'
    union all select 'B',2,'d'
    union all select 'B',3,'e'
    union all select 'B',4,'f'
    go--查询
    declare @s nvarchar(4000)
    set @s=''
    select @s=@s+','+quotename(编号)
    +'=isnull(max(case 编号 when '+rtrim(编号)
    +' then 值 end),'''')'
    from A
    group by 编号
    exec('select 类型'+@s+' from A group by 类型')
    go--删除测试
    drop table A/*--结果
    类型         1          2          3          4          
    ---------- ---------- ---------- ---------- ---------- 
    A          a          b          c          
    B                     d          e          f
    --*/
      

  2.   

    老大就是老大,我看了半天就是没看懂
    ,[1]=isnull(max(case 编号 when 1 then 值 end),'')
    ,[2]=isnull(max(case 编号 when 2 then 值 end),'')
    ,[3]=isnull(max(case 编号 when 3 then 值 end),'')
    ,[2]=isnull(max(case 编号 when 2 then 值 end),'')
    ,[3]=isnull(max(case 编号 when 3 then 值 end),'')
    ,[4]=isnull(max(case 编号 when 4 then 值 end),'')
    这些是什么意思能解释一下吗?
    有这么多列会什么最后就只有1,2,3,4这四列了啊???
      

  3.   

    跟据上面写的
    @s应该为,[1]=isnull(max(case 编号 when 1 then 值 end),'')
    ,[2]=isnull(max(case 编号 when 2 then 值 end),'')
    ,[3]=isnull(max(case 编号 when 3 then 值 end),'')
    ,[2]=isnull(max(case 编号 when 2 then 值 end),'')
    ,[3]=isnull(max(case 编号 when 3 then 值 end),'')
    ,[4]=isnull(max(case 编号 when 4 then 值 end),'')我直接写出来为什么结果集出来不对啊,语句如下;
    select 类型,[1]=isnull(max(case 编号 when 1 then 值 end),'')
    ,[2]=isnull(max(case 编号 when 2 then 值 end),'')
    ,[3]=isnull(max(case 编号 when 3 then 值 end),'')
    ,[2]=isnull(max(case 编号 when 2 then 值 end),'')
    ,[3]=isnull(max(case 编号 when 3 then 值 end),'')
    ,[4]=isnull(max(case 编号 when 4 then 值 end),'')
    from A group by 类型
    结果集为
    A a b c b c
    B d e d e f