Sum multiple columns when column has NULL value in SQL Server

Last Reply 4 months ago By dharmendr

Posted 4 months ago

Hi!

How I can get sum two columns from table when it is null.

declare @Result table (id int, smoney float, fmoney float)
insert into @Result(id, smoney, fmoney)values(1, 3500, null) 
insert into @Result(id, smoney, fmoney)values(2, 3000, null)
insert into @Result(id, smoney, fmoney)values(3, 2500, null)

select sum(sum(smoney)+sum(fmoney))summa from @Result
select * from @Result

 

Posted 4 months ago

Hi PRA,

You need to use ISNULL function.

Refer below query.

SQL

DECLARE @Result TABLE (id INT, smoney FLOAT, fmoney FLOAT)
INSERT INTO @Result(id, smoney, fmoney)VALUES(1, 3500, null)
INSERT INTO @Result(id, smoney, fmoney)VALUES(2, 3000, null)
INSERT INTO @Result(id, smoney, fmoney)VALUES(3, 2500, null)
 
SELECT id,ISNULL(smoney,0)+ISNULL(fmoney,0)summa FROM @Result

Output

id summa
1 3500
2 3000
3 2500