Sandeep
Sandeep

Reputation: 2593

Issue with using SUM function in SQL

I am using

select sum(value1-value2) as Result from tbl

it is working fine but when I try to use

select id,name,sum(value1-value2) as Result from tbl

it does not work.

What can be the solution?

Upvotes: 0

Views: 83

Answers (2)

akbarbin
akbarbin

Reputation: 5105

when you using sum(), you should add group by

select id,name,sum(value1-value2) as Result
from tbl
group by id, name

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269473

You need a group by if you want the value for each id/name:

select id, name, sum(value1-value2) as Result
from tbl
group by id, name;

Otherwise, you need to put them in aggregate functions:

select min(id), min(name), sum(value1-value2) as Result
from tbl;

Or, if you just want the difference on each row, then omit the sum():

select id, name, (value1-value2) as Result
from tbl;

Upvotes: 4

Related Questions