Home > Database > Mysql Tutorial > How to Correctly Calculate the Average of Multiple Columns with NULL Values in SQL Server?

How to Correctly Calculate the Average of Multiple Columns with NULL Values in SQL Server?

DDD
Release: 2024-12-27 04:08:10
Original
886 people have browsed it

How to Correctly Calculate the Average of Multiple Columns with NULL Values in SQL Server?

Average of Multiple Columns

When calculating the average of multiple columns in a table, it's crucial to handle nullability correctly. Consider the following situation:

Problem:

You have a table called "Request" with the following data:

Req_ID    R1   R2   R3   R4   R5
R12673    2    5    3    7    10
R34721    3    5    2    1    8
R27835    1    3    8    5    6
Copy after login

You want to display the average of the columns R1, R2, R3, R4, and R5. However, when you use the following query:

Select Req_ID, Avg(R1+R2+R3+R4+R5) as Average
from Request
Group by Req_ID
Copy after login

You get the sum of the values instead of the average.

Solution:

The issue lies in the handling of NULL values. If your columns allow NULLs, the sum of NULLs is also NULL. To calculate the average correctly, you need to ignore the NULLs.

Post-2008 Syntax:

If you're using SQL Server 2008 or later, you can use the following syntax:

SELECT *,
       (SELECT AVG(c)
        FROM   (VALUES(R1),
                      (R2),
                      (R3),
                      (R4),
                      (R5)) T (c)) AS [Average]
FROM   Request
Copy after login

This syntax uses the VALUES clause to construct a table with one row for each column. The AVG aggregate is then applied to this table, ignoring any rows that contain NULL values.

Pre-2008 Syntax:

If you're using SQL Server 2005 or earlier, you can use the following syntax:

SELECT *,
       (SELECT AVG(c)
        FROM   (SELECT R1
                UNION ALL
                SELECT R2
                UNION ALL
                SELECT R3
                UNION ALL
                SELECT R4
                UNION ALL
                SELECT R5) T (c)) AS [Average]
FROM   Request
Copy after login

This syntax uses UNION ALL to create a table with one row for each column. The AVG aggregate is then applied to this table, ignoring any rows that contain NULL values.

The above is the detailed content of How to Correctly Calculate the Average of Multiple Columns with NULL Values in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template