How to average 3 values ββin Sql Server?
I have three variables: -
@ScoreA DECIMAL(10,7)
@ScoreB DECIMAL(10,7)
@ScoreC DECIMAL(10,7)
@FinalScore DECIMAL(10, 7)
I want to get an average of three points. BUT 1, 2, or all 3 values ββcan be zero.
Eg. Scenarios:
- A = 1.4, B = 3.5, C = 5.0; FinalScore = 3.3
- A = 0.0, B = 0.0, C = 0.0; FinalScore = 0.0
- A = 1.1, B = 0.0, C = 0.0; FinalScore = 1.1
- A = 0.0, B = 2.0, C = 4.8; FinalScore = 3.4
Hooray!
+2
source to share
3 answers
IF @A > 0 OR @B > 0 OR @C > 0
SELECT ((@A + @B + @C) /
(0 +
CASE WHEN @A = 0 THEN 0 ELSE 1 END +
CASE WHEN @B = 0 THEN 0 ELSE 1 END +
CASE WHEN @C = 0 THEN 0 ELSE 1 END ))
ELSE
SELECT 0.0
EDIT
The modified query now handles division by a null scenario.
EDIT2
Here is the "AVG (..) function trick" :) with the Common Table expression
WITH T(I) AS (SELECT @A UNION SELECT @B UNION SELECT @C)
SELECT AVG(I) FROM T
WHERE I > 0
+1
source to share
It's easier for me to read and understand:
DECLARE
@ScoreA DECIMAL(10,7),
@ScoreB DECIMAL(10,7),
@ScoreC DECIMAL(10,7),
@FinalScore DECIMAL(10, 7)
SET @ScoreA = 1.4
SET @ScoreB = 3.5
SET @ScoreC = 5.0
DECLARE
@AVG TABLE (value DECIMAL(10,7))
INSERT INTO @AVG
SELECT @ScoreA WHERE @ScoreA > 0
UNION
SELECT @ScoreB WHERE @ScoreB > 0
UNION
SELECT @ScoreC WHERE @ScoreC > 0
SELECT COALESCE(AVG(value), 0) FROM @AVG
0
source to share