在SQL Server中对SUM函数应用OR条件

时间:2018-03-20 04:55:44

标签: sql sql-server tsql

我有2列名为DebitCredit。我想从一列中获取值并放入第三列Balance。我想应用一个条件,如果Debit包含任何值,则应将其放在Balance列中,如果Credit有某些内容,则应将该值插入列中,但如果两者都有一些值,那么只有一个值应该去DebitCredit

Debit    Credit     Balance
------------------------------
1000     NULL       1000
2200     NULL       2200
NULL     3000       3000
1500     1500       1500

查询:

SELECT 
       Debit, Credit, SUM(Credit|Debit) AS Balance
FROM Table

3 个答案:

答案 0 :(得分:5)

例如COALESCE()就足够了

SELECT Debit, Credit, COALESCE(Credit, Debit) AS Balance
FROM Table

答案 1 :(得分:2)

如果我理解正确,你正在寻找类似的东西。

SELECT Debit, Credit,     
(
 CASE WHEN Credit IS NOT NULL THEN Credit      
 ELSE Debit 
 END
)  AS Balance
FROM [Table]

答案 2 :(得分:2)

declare @tab table(Debit int,Credit int)

insert into @tab
select 1000  ,   NULL
union all   
select 2200   ,  NULL  
union all 
select NULL  ,   3000  
union all 
select 1500  ,   1500   


SELECT Debit, Credit,
CASE WHEN Debit is null then Credit
 WHEN Credit is null then Debit else Debit end AS Balance
FROM @tab

输出

Debit   Credit  Balance
1000    NULL    1000
2200    NULL    2200
NULL    3000    3000
1500    1500    1500