2011-04-09 22 views
0

中我有虚表的数据如下:准备项目列表的SQL表

Name      amount  amount1 
----------------------------------------------- 
mahesh      1200  Null 
mahesh      1000  Null 
mahesh      Null  25000 
mahendra     1200  Null 
Kirti      null  22000 

我想准备像下面的列表:

Name      amount  amount1 
----------------------------------------------- 
mahesh         22800 
mahendra     1200 
kirti         22000 

怎么办呢? 什么是sql交易?

回答

3

看起来您正在添加数字,其中amount为负数,amount1为正数。你可以用group by来做到这一点。一个case可以帮助地方所产生的sum在右列:

select name 
,  case 
     when sum(amount1 - amount) < 0 then -sum(amount1 - amount) 
     end as amount 
,  case 
     when sum(amount1 - amount) >= 0 then sum(amount1 - amount) 
     end as amount1 
from YourTable 
group by 
     name 
+0

是你的想法是点击高达一些点,但我freinds你缺少表名和凝聚或为空函数 – mahesh 2011-04-09 10:34:36

+0

...也马亨德拉的结果,你的代码显示 - 1200金额,我不想在它的负面迹象。 – mahesh 2011-04-09 10:36:16

+0

@mahesh:我已经添加了'from'子句,并将第一列写入正面 – Andomar 2011-04-09 11:13:36

0

该解决方案通过Andomar与凝聚作用下激发的:

select name,  
case 
when sum(coalesce(amount1,0) - coalesce(amount,0)) < 0 
then -sum(coalesce(amount1,0) - coalesce(amount,0)) 
end 
as amount,  
case 
when sum(coalesce(amount1,0) - coalesce(amount,0)) >= 0 
then sum(coalesce(amount1,0) - coalesce(amount,0)) 
end 
as amount1 
from dummy 
group by 
name 

聚结或者ISNULL功能是需要数第一可以为空的列。 否则你的结果应该保持NULL