准备Sql-Table的项目列表

时间:2011-04-09 09:57:58

标签: 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 transact?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

此解决方案的灵感来自Andomar的Coalesce Function,如下所示:

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

需要COALESCE或ISNULL函数来计算第一个可以为空的列。 否则您的结果应保持为 NULL