本帖最后由 luckdwj 于 2012-03-08 11:02:18 编辑

解决方案 »

  1.   

    已经给出思路了 筛选你要的结果放到临时表里然后经典行列转换。
    http://blog.csdn.net/szstephenzhou/article/details/7091819
      

  2.   


    --> 测试数据:[A1]
    go
    if object_id('[A1]') is not null 
    drop table [A1]
    go
    create table [A1](
    [id] int,
    [num] int,
    [class] varchar(5)
    )
    go
    insert [A1]
    select 1,10,'类别1' union all
    select 1,101,'类别2' union all
    select 2,20,'类别1' union all
    select 2,50,'类别1'--> 测试数据:[B1]
    go
    if object_id('[B1]') is not null 
    drop table [B1]
    create table [B1](
    [id] int,
    [num] int,
    [class] varchar(5)
    )
    go
    insert [B1]
    select 1,100,'类别1' union all
    select 1,1001,'类别2' union all
    select 1,1000,'类别3' union all
    select 2,20,'类别1' union all
    select 2,20,'类别2'go
    create table #t(
    id int,
    numa int,
    numb int,
    class varchar(5)
    )
    insert #t
    select b.id,sum(isnull(a.num,0)) as numa,sum(isnull(b.num,0)) as numb,b.class
    from [B1] b left join [A1] a
    on b.id=a.id group by  b.id,b.class
    select * from #tdeclare @str varchar(1000)
    set @str=''
    select @str=@str+','+class+'=sum(case when class='
         +QUOTENAME(class,'''')+'then numa+numb else 0 end)'
    from #t group by class
    set @str='select id'+@str+' from #t group by id'
    exec(@str)
    ----------------------------------
    id 类别1 类别2 类别3
    1 311 2113 2111
    2 110 110 0
      

  3.   

    单个表的按分类行转列已经写出来了  想把这两份数据统一下因为A和B的id不确定一样  同id下的分类也不确定一样  写的筛选语句成是交集了  不是合集