MS SQL Server - stored procedure help

Associate
Joined
6 Jan 2006
Posts
1,024
Location
Midlands
I have a basic select statement i.e.

SELECT
ID, A, B, C
FROM
tblScores

I would like to also return the sum of A,B,C AS 'Total'

However A,B or C can be nulls

I assume i would have to check for nulls and then them together? How do i achieve this?
 
You can't return the SUM as well as the actual values in one query but to get the sum do
SELECT
ID, SUM(ISNULL(A, 0)) + SUM(ISNULL(B, 0)) + SUM(ISNULL(C, 0)) AS [Total]
FROM
tblScores
GROUP BY ID
 
Last edited:
You can return the lot with this subquery.

Code:
SELECT s.ID, s.A, s.B, s.C, sub.Total
FROM tblScores s
INNER JOIN 
	(SELECT s.ID, SUM(ISNULL(s.A, 0)) + SUM(ISNULL(s.B, 0)) + SUM(ISNULL(s.C, 0)) AS [Total]
	FROM tblScores s GROUP BY s.ID) sub
ON s.ID = sub.ID
 
Thanks! Appreciate the help.

Had to take out the Sum keyword to get it to work.

SELECT
ID, (ISNULL(A, 0)) + (ISNULL(B, 0)) + (ISNULL(C, 0)) AS [Total]
FROM
tblScores
 
SUM is used to get the sum of values from all rows - sounds like that isn't what you want.

As far as I can see, you just need this, it's pretty straightforward:

Code:
select
	id,
	a,
	b,
	c,
	isnull(a,0)+isnull(b,0)+isnull(c,0) as total
from
	TABLE
 
Back
Top Bottom