Pure.Krome
Pure.Krome

Reputation: 86987

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 wish to get the average of the three scores. BUT 1, 2 or all 3 values might be zero.

Eg. scenarios:

Cheers!

Upvotes: 2

Views: 3867

Answers (3)

Svetlozar Angelov
Svetlozar Angelov

Reputation: 21670

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

Modified query to now handle divide by zero scenario's.

EDIT2

Here is "the trick with the AVG(..) function" :) with Common Table Expression

WITH T(I) AS (SELECT @A UNION SELECT @B UNION SELECT @C)
SELECT AVG(I) FROM T
WHERE I > 0

Upvotes: 1

Grzegorz Gierlik
Grzegorz Gierlik

Reputation: 11232

For me this is easier 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

Upvotes: 0

kaiz.net
kaiz.net

Reputation: 1994

SELECT ((@A + @B + @C) / 
        (CASE WHEN (@A = 0.0 AND @B = 0.0 AND @C = 0.0) THEN 1 ELSE 0 END 
        + 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 
        )
      )

Upvotes: 1

Related Questions