Skip to content
Advertisement

Average across rows in SQL Server 2008

I have the following table

Data   Data1  Data2  YTD
-------------------------
1       2      3      
2       3      4     
3       3      6  

In the YTD column I have to average the rows data. I can use average in columns but not sure how to average across rows.

Looking for the below results and using SQL Server 2008

 Data   Data1  Data2  YTD
 ---------------------------------
    1       2      3   2 (Average)   
    2       3      4   3 
    3    null      6   4.5

Advertisement

Answer

I think cross apply is the simplest method:

select t.*, v.avg_data
from t cross apply
     (select avg(v.data) as avg_data
      from (values (t.data), (t.data1), (t.data2)) v(data)
     ) v;

Use case expressions, you can also express this as:

select t.*,
       ( (coalesce(t.data, 0) + (t.data1, 0) + coalesce(t.data2, 0)) /
         nullif( (case when t.data is not null then 1 else 0 end) +
                 (case when t.dat1 is not null then 1 else 0 end) +
                 (case when t.dat2 is not null then 1 else 0 end), 0
               )
       ) as avg_data;

However, this formulation is messy and prone to typing errors.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement