table 
id     money    tepy
001     100      1
001     150      2
001     150      3
002     100      2
003     100      1
003     100      3
004     200      1说明:当tepy=1、2时 money 相加,当tepy=3时 money 减
结果id    money    
001    100
002    100
003     0
004    200

解决方案 »

  1.   

    SELECT ID,SUM(CASE WHEN TEPY=3 THEN 0-[MONEY] ELSE [MONEY] END)
    FROM TB
    GROUP BY ID
      

  2.   

    select id,sum(money) as [money]
    from (select id,case when tepy in (1,2) then money else -money end as money from [table])k
    group by id
      

  3.   


    select id,sum(case tepy when 3 then -money 
    else money end) money   
    from table
    group by id
      

  4.   

    if object_id('[t]') is not null drop table [t]
    go
    create table [t] ([id] varchar(3),[money] int,[tepy] int)
    insert into [t]
    select '001',100,1 union all
    select '001',150,2 union all
    select '001',150,3 union all
    select '002',100,2 union all
    select '003',100,1 union all
    select '003',100,3 union all
    select '004',200,1
    select ID,
           sum([money])[money]
    from
    (
    select ID,
           sum([money])[money] 
    from [t]
    where tepy in (1,2)
    group by ID
    union all
    select ID,
           -sum([money])[money] 
    from [t]
    where tepy =3
    group by ID)t
    group by ID
    /*
    ID   money
    ---- -----------
    001  100
    002  100
    003  0
    004  200(4 個資料列受到影響)
    */