SELECT CompanyID,
       sum(case when Type = 1 then TotalFee end) Type(1),
       sum(case when Type = 2 then TotalFee end) Type(2),
       sum(case when Type = 3 then TotalFee end) Type(3)
FROM TB_Fee 
GROUP BY CompanyID

解决方案 »

  1.   

    select CompanyID,sum(case when Type =1 then TotalFee end) as [type(1)],
     sum(case when Type =2 then TotalFee end) as [type(2)],
    sum(case when Type =3 then TotalFee end) as [type(3)]
    from TB_Fee group by CompanyID
      

  2.   


    declare @sql varchar(8000)
    set @sql = 'select CompanyID'
    select @sql = @sql + ',sum(case Type when '''+Type+''' then cj end) [Type('+Type+')]'
     from (select distinct Type from TB_Fee ) as a
    select @sql = @sql+' from TB_Fee  group by CompanyID'
    exec(@sql)
      

  3.   

    修改以下
    declare @sql varchar(8000)
    set @sql = 'select CompanyID'
    select @sql = @sql + ',sum(case Type when '''+Type+''' then TotalFee end) [Type('+Type+')]'
     from (select distinct Type from TB_Fee ) as a
    select @sql = @sql+' from TB_Fee  group by CompanyID'
    exec(@sql)
      

  4.   

    SELECT CompanyID,
           sum(case when Type = 1 then TotalFee else ''end) Type(1),
           sum(case when Type = 2 then TotalFee else ''end) Type(2),
           sum(case when Type = 3 then TotalFee else ''end) Type(3)
    FROM TB_Fee 
    GROUP BY CompanyID order by CompanyID