select 姓名,商用=sum(case when 名称='商用' then 费用 else 0 end),
            民用=sum(case when 名称='民用' then 费用 else 0 end),
            sum(费用) as 费用合计
from tbl
group by 姓名

解决方案 »

  1.   

    select isnull(a.姓名,b.姓名) as 姓名,
           a.费用 as 商用,
           b.费用 as 民用,
           a.费用+b.费用 as 费用合计
    from 表 (select 姓名,sum(费用) as 费用 from 表 where 名称='商用' group by 姓名) a
            full join 
            (select 姓名,sum(费用) as 费用 from 表 where 名称='商用' group by 姓名) b
         on a.姓名=b.姓名
      

  2.   

    select isnull(a.姓名,b.姓名) as 姓名,
           a.费用 as 商用,
           b.费用 as 民用,
           a.费用+b.费用 as 费用合计
    from 表 (select 姓名,sum(费用) as 费用 from 表 where 名称='商用' group by 姓名) a
            full join 
            (select 姓名,sum(费用) as 费用 from 表 where 名称='民用' group by 姓名) b
         on a.姓名=b.姓名
      

  3.   

    先建立一個function 
    create function  getqty(@k  varchar(10),@i  varchar(10))  
    returns  varchar(500)
    as
    begin
    declare  @s  varchar(500)
    set @s=''
    Select @s=@s+cast(費用 as varchar(10))+' + '  from  test1 where  姓名=@k  and 名稱=@i
    set @s=substring(@s,1,len(@s)-1)
    return(@s)
    -----------------------------------------------------
    select 姓名,商用=cast((
    Select sum(費用) from test1 Where 姓名=a.姓名  and 名稱='商用'  group by 姓名,名稱
    )  as varchar(10))+dbo.getqty(姓名,'商用'),
    民用=cast((
    Select sum(費用) from test1 Where 姓名=a.姓名  and 名稱='民用'  group by 姓名,名稱
    )  as varchar(10))+dbo.getqty(姓名,'民用'),費用合計=sum(費用)
         from 表 a  group by 姓名end
    然後再進行 一條sql語句