表结构
Tab1 ID    ST_Name     ST_Fee 
1024   费用1    10.10
1024   费用1       20
1025   费用1       10.15
1026   费用2       14
1025   费用2       12我现在是用的
select ID,Max(case when Fee_Name='费用1' then ST_Fee else 0 end) from Fee_sHEET GROUP BY ID可查询的结果费用1显示是10.10,我要的应该是二条费用1为 1024的合计,请问怎么改代码,谢谢,在线等待

解决方案 »

  1.   

    //这样吗?
    select id,st_name,st_fee from tab1 a where st_name='费用1'
    and not exists(select 1 from tab1 where id=a.id and st_nama=a.st_name and st_fee>a.st_fee)
      

  2.   


    如有要合计金额的话,应该用SUM,而不是MAX
    ---测试数据---
    if object_id('[Tab1]') is not null drop table [Tab1]
    go
    create table [Tab1]([ID] int,[ST_Name] varchar(5),[ST_Fee] numeric(4,2))
    insert [Tab1]
    select 1024,'费用1',10.10 union all
    select 1024,'费用1',20 union all
    select 1025,'费用1',10.15 union all
    select 1026,'费用2',14 union all
    select 1025,'费用2',12
     
    ---查询---
    select 
      ID,
      SUM(case when ST_Name='费用1' then ST_Fee else 0 end) AS [费用1],
      SUM(case when ST_Name='费用2' then ST_Fee else 0 end) AS [费用2]
    from Tab1 
    GROUP BY ID ---结果---
    ID          费用1                                     费用2
    ----------- --------------------------------------- ---------------------------------------
    1024        30.10                                   0.00
    1025        10.15                                   12.00
    1026        0.00                                    14.00(3 行受影响)
      

  3.   


    如果是合计的话,应该用SUM,而不是MAX.
    select ID,
           sum(case Fee_Name when '费用1' then ST_Fee else 0 end) [费用1],
           sum(case Fee_Name when '费用2' then ST_Fee else 0 end) [费用2]
    from Fee_sHEET 
    GROUP BY ID  
      

  4.   

    怎么会用max呢?这样是求最大值
    要用sum求和么!
      

  5.   

    因为case语句当Fee_Name为‘费用'时取值,如果不是取0,比如有:10.10,0,0,0;求和不就是10.10吗?