ID          flag         cishu
003         128           3
003          5            6
007          5            6
007          2            7
003          2            9           
flag='128'表示手工充值,flag='5'表示补贴,flag='2'表示月消费;
解释一下上面数据:003这个人手工充值了3次,补贴6次,那么他这个月消费了9次是正常的,而007这个人就补贴了6次却消费了7次,说明他超出了消费,多消费了一次。现在要算出手工充值+补贴〉月消费的值,代码应该怎么写?希望计算公式这块能写清楚点。谢谢了

解决方案 »

  1.   


    select 
    sum(case when flag='2' then cishu else 0 end)-sum(case when flag in ('5','128') then cishu else 0 end)
    as [手工充值+补贴〉月消费的值]
    from tb
      

  2.   

    写反了select 
    sum(case when flag in ('5','128') then cishu else 0 end)-sum(case when flag='2' then cishu else 0 end)
    as [手工充值+补贴〉月消费的值]
    from tb
      

  3.   

    --> 测试数据:[tbl]
    if object_id('[tbl]') is not null drop table [tbl]
    create table [tbl]([ID] varchar(3),[flag] int,[cishu] int)
    insert [tbl]
    select '003',128,3 union all
    select '003',5,6 union all
    select '007',5,6 union all
    select '007',2,7 union all
    select '003',2,9
    select [ID] from(
    select [ID],case [flag] when 128 then [cishu] when 5 then [cishu]
    else -[cishu] end as [cishu] from tbl)a group by ID having SUM(cishu)>=0
     
      

  4.   


    select [ID] from(
    --使用case when判断是从之或者补贴,是为正数,不是为负数
    select [ID],case [flag] when 2 then -[cishu] else cishu end as [cishu] 
    from tbl)a 
    group by ID having SUM(cishu)>=0
      

  5.   


    use tempdbcreate table mytest
    (
    code varchar(10),
    flag int,
    num int
    )insert into mytest(code ,flag,num) values('003',128,3)
    insert into mytest(code ,flag,num) values('003',5,6)
    insert into mytest(code ,flag,num) values('007',5,6)
    insert into mytest(code ,flag,num) values('007',2,7)
    insert into mytest(code ,flag,num) values('003',2,9)
    insert into mytest(code ,flag,num) values('008',128,9)SELECT * FROM mytestwith  temptb as
    (
    SELECT code,sum(num) as num from mytest where flag=128 or flag=5
    group by code
    ),
     temptt as
    (
    SELECT code,sum(num) as tnum from mytest where flag !=128 and flag!=5
    group by code
    )SELECT tb.code,tb.num,tt.tnum FROM temptb as tb
    left join temptt as tt
    on tb.code=tt.code
     where (tb.num-tt.tnum)>=0 or tt.tnum is null /*
    code       num         tnum
    ---------- ----------- -----------
    003        9           9
    008        9           NULL
    */