日期:2014-05-18  浏览次数:20456 次

新人,帮忙看下。。
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次,说明他超出了消费,多消费了一次。

现在要算出手工充值+补贴〉月消费的值,代码应该怎么写?希望计算公式这块能写清楚点。谢谢了

------解决方案--------------------
SQL code

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

------解决方案--------------------
SQL code


--> 测试数据:[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