declare @s varchar(8000)
set @s='select tu_date=str_date'
select @s=@s+',['+str_name+']=sum(case when str_num '''+str_name+''' then str_num else 0 end)' from tb group by str_name
set @s=@s+' from tb group by str_date order by str_date'
exec(@s)

解决方案 »

  1.   

    --测试表及数据
    create table table1(str_date int,str_num int,str_name varchar(10))
    insert into table1
    select 1,            34         ,'A' union all
    select 1,             34         ,'A' union all
    select 1,             25         ,'B' union all  
    select 2,             21         ,'B' union all
    select 2,             34         ,'A' union all
    select 2,             45         ,'C' union all
    select 2,             23         ,'C' 
    --处理语句
    declare @sql varchar(8000)
    select @sql=''
    select @sql=@sql+',sum(case str_name when '''+str_name+''' then str_num else 0 end) as '+str_name
    from table1
    group by str_name
    exec('select str_date'+@sql+' from table1 group by str_date')
    --删除测试表
    drop table table1/*结果
    1 68 25 0
    2 34 21 68*/
      

  2.   

    select str_date as tu_date,sum((select str_name from tablename where str_name='A')) as A,sum((select str_name from tablename where str_name='B')) as B,sum((select str_name as C from tablename where str_name='C')) as C from tablename group by str_date