有表如下:
Name Score
AA   50
AA   -20
AA   40
AA   -25想通过一个SQL语句实现这样的查询:
Name ZScore FScore
AA   90     -45谢谢

解决方案 »

  1.   

    select 
        Name,
        ZScore=sum(case when Score>0 then Score else 0 end),
        FScore=sum(case when Score<0 then Score else 0 end)
    from
        表 
    group by 
        Name
      

  2.   

    declare @t table(Name varchar(4),Score int)
    insert into @t select 'AA',50
    insert into @t select 'AA',-20
    insert into @t select 'AA',40
    insert into @t select 'AA',-25select 
        Name,
        ZScore=sum(case when Score>0 then Score else 0 end),
        FScore=sum(case when Score<0 then Score else 0 end)
    from
        @t 
    group by 
        Name/*
    Name ZScore      FScore      
    ---- ----------- ----------- 
    AA   90          -45
    */
      

  3.   


    create table T(name varchar(100), score int)
    insert into T
    select 'AA',   50 union all
    select 'AA',   -20 union all
    select 'AA',   40 union all
    select 'AA',   -25select 
        Name,
        sum(case when Score>0 then Score else 0 end) as ZScore,
        sum(case when Score<0 then Score else 0 end) as FScore
    from T 
    group by Namedrop table T
      

  4.   

    select name ,sum(case when score>0 then score else 0 end )as ZScore,sum(case when score<0 then score else 0 end )as FScore from 表名 group by name
      

  5.   

    create table tb(
    name varchar(10),
    Score int
    )insert tb select 'AA', 50union all select 'AA',   -20
    union all select 'AA',   40
    union all select 'AA',   -25select Name,
    ZScore=sum( case when Score>0 then Score end),
    FScore=sum(case when Score<0 then Score end)
    from tb
    group by Name
      

  6.   

    来晚了,顺便接点分~谢谢~有什么问题再提出来
    select name ,sum(case when score>0 then score else 0 end )as ZScore,sum(case when score<0 then score else 0 end )as FScore from tablename group by name