通过一个查询结果得到表A:分类1 分类2  数值
1      A      100
2      A      200
3      A      300
1      B      400
2      B      500
3      B      600
现需要得到表B:
分类1   A数值  B数值   
1        100    400
2        200    500
3        300    600并且分类2的下面列不固定,也就是说,不仅仅有A,B 2种,是动态的.分类1是确定的.求解.感谢.费解了一上午了.

解决方案 »

  1.   


    if OBJECT_ID('表A') is not null
    drop table 表A
    go
    create table 表A (分类1 int,分类2 varchar(2),数值 int)
    insert into 表A
    select 1, 'A', 100 union all
    select 2, 'A', 200 union all
    select 3, 'A', 300 union all
    select 1, 'B', 400 union all
    select 2, 'B', 500 union all
    select 3, 'B', 600
    declare @s varchar(8000)
    set @s=''
    select @s=@s+','+ 分类2+'数值= sum(case 分类2 when '''+分类2+''' then 数值 else 0 end)'
    from 表A
    group by 分类2
    exec ('select 分类1 '+@s+' from 表A group by 分类1')
    分类1 A数值 B数值
    1 100 400
    2 200 500
    3 300 600