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


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 
        )
      )

      



0


source


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







All Articles