SQL sum of 3 columns -
i know question might seem little basic stuff want make sure right syntax because line of code run often:
i want sum columns a, b , c of table "alphabet" rows have id included in in clause.
this how i'd confirmation if possible:
select sum(a + b + c) "subtotal" alphabet id in ('1','5','378');
if id
not string, shouldn't quote values.
select sum(a + b + c) "subtotal" alphabet id in (1,5,378);
this should work, may may have 1 non-obvious consequence. if row has a
not null , 1 of others null, row drop out of summation because null plus else null, , nulls ignored sum
operator. may safer write:
select sum(a) + sum(b) + sum(c) "subtotal" alphabet id in (1,5,378);
this suffers same potential problem, less happen because entire column have null. there various dialect specific ways defend against problem if still concerned. portable painfully verbose:
select sum( case when null 0 else end + case when b null 0 else b end + case when c null 0 else c end ) "subtotal" alphabet id in (1,5,378);
Comments
Post a Comment