declare @s varchar(8000)
set @s=''
select @s=@s+','+quotename(费用名)+'=sum(case b.费用名 when '+quotename(费用名,'''')+' then b.费用 end)'
from B表
group by 费用名
exec('select a.姓名,a.性别'+@s+'
from A表 a,B表 b
where a.姓名=b.姓名
group by a.姓名,a.性别')

解决方案 »

  1.   

    --费用名固定,则直接使用select a.姓名,a.性别,
    饮料费=sum(case b.费用名 when '饮料费' then b.费用 end),
    车费=sum(case b.费用名 when '车费' then b.费用 end),
    购衣费=sum(case b.费用名 when '购衣费' then b.费用 end)
    from A表 a,B表 b
    where a.姓名=b.姓名
    group by a.姓名,a.性别
      

  2.   

    declare @s varchar(8000)
    set @s=''
    select @s=@s+','+quotename(费用名)+'=sum(case b.费用名 when '+quotename(费用名,'''')+' then b.费用 end)'
    from B表
    group by 费用名
    exec('select a.姓名,a.性别'+@s+'
    from A表 a,B表 b
    where a.姓名=b.姓名
    group by a.姓名,a.性别')