select 年度,编号,'酒水' as 费用名称1,
sum(case when 费用名称 = '酒水' then 金额  else 0 end) as 金额1,
'差旅' as 费用名称2,
sum(case when 费用名称 = '差旅' then 金额  else 0 end) as 金额2,
sum(金额) as 总金额
from 表
group by 年度,编号

解决方案 »

  1.   

    --如果费用名称固定为:酒水,差旅
    --可以用:select 年度,编号
      ,费用名称1='酒水',金额1=sum(case 费用名称 when '酒水' then 金额 else 0 end)
      ,费用名称2='差旅',金额2=sum(case 费用名称 when '差旅' then 金额 else 0 end)
      ,总金额=sum(金额)
    from 表 group by 年度,编号
      

  2.   

    --如果不固定,就要用动态SQL语句.
    declare @s varchar(8000)
    set @s=''
    select @s=@s+',[费用:'+费用名称+']='''+费用名称+''',[金额:'+费用名称+']=sum(case  费用名称 when '''+费用名称+''' then 金额 else 0 end)'
    from(select distinct 费用名称 from 表) a
    exec('select 年度,编号'+@s+'
    ,总金额=sum(金额)
    from 表 group by 年度,编号')
      

  3.   

    --上面的错了一点,改一下:
    declare @s varchar(8000)
    set @s=''
    select @s=@s+',[费用:'+费用名称+']='''+费用名称+''',[金额:'+费用名称+']=sum(case 费用名称 when '''+费用名称+''' then 金额 else 0 end)'
    from(select distinct 费用名称 from 表) a
    exec('select 年度,编号'+@s+'
    ,总金额=sum(金额)
    from 表 group by 年度,编号')
      

  4.   

    --下面这个考虑了,如果金额为0,显示为无的情况--如果不固定,就要用动态SQL语句.
    declare @s varchar(8000),@s1 varchar(8000)
    select @s='',@s1=''
    select @s=@s+',[费用:'+费用名称+']='''+费用名称
    +''',[金额:'+费用名称+']=sum(case 费用名称 when '''
    +费用名称+''' then 金额 else 0 end)'
    ,@s1=@s1+',[费用:'+费用名称+']=case [金额:'
    +费用名称+'] when 0 then ''无'' else '''+费用名称
    +''' end,[金额:'+费用名称+']'
    from(select distinct 费用名称 from 表) aexec('select 年度,编号'+@s1+',总金额 from(
    select 年度,编号'+@s+'
    ,总金额=sum(金额)
    from 表 group by 年度,编号
    ) a')
    go
      

  5.   

    --下面是测试--测试数据
    create table 表(年度 int,编号 varchar(2),费用名称 varchar(10),金额 int)
    insert into 表
    select 2002,'01','酒水',5000
    union all select 2002,'01','差旅',3000
    union all select 2003,'01','酒水',6000
    union all select 2003,'02','酒水',3500
    union all select 2003,'02','差旅',5000
    go--查询处理
    declare @s varchar(8000),@s1 varchar(8000)
    select @s='',@s1=''
    select @s=@s+',[费用:'+费用名称+']='''+费用名称
    +''',[金额:'+费用名称+']=sum(case 费用名称 when '''
    +费用名称+''' then 金额 else 0 end)'
    ,@s1=@s1+',[费用:'+费用名称+']=case [金额:'
    +费用名称+'] when 0 then ''无'' else '''+费用名称
    +''' end,[金额:'+费用名称+']'
    from(select distinct 费用名称 from 表) aexec('select 年度,编号'+@s1+',总金额 from(
    select 年度,编号'+@s+'
    ,总金额=sum(金额)
    from 表 group by 年度,编号
    ) a')
    go--删除测试
    drop table 表/*--测试结果
    年度          编号   费用:差旅 金额:差旅       费用:酒水 金额:酒水       总金额         
    ----------- ---- ----- ----------- ----- ----------- ----------- 
    2002        01   差旅    3000        酒水    5000        8000
    2003        01   无     0           酒水    6000        6000
    2003        02   差旅    5000        酒水    3500        8500
    --*/