简体   繁体   English

计算每行的平均值,然后计算每列的平均值

[英]Calculate average per row and then calculate average per column

I have a table shown below 我有下面的表格

Col1    Col2    Col3    Col4
NULL    NULL    NULL    54.84
NULL    NULL    NULL    75.40
57.24   73.61   NULL    NULL

I want to first calculate the average of the row and then calculate the final average of the column 我想先计算行的平均值,然后再计算列的最终平均值

So my calculation becomes 所以我的计算成为

    Row1Avg   54.84
    Row2Avg   75.40
    Row3Avg   65.42

And then I arrive at the final average of Row1Avg,Row2Avg,Row3Avg = 65.22 然后我得出Row1Avg,Row2Avg,Row3Avg = 65.22的最终平均值Row1Avg,Row2Avg,Row3Avg = 65.22

Can some please tell me how to achieve this in an efficient manner. 可以请我告诉我如何有效地实现这一目标。 How I was thinking of doing it is I have a temp table with single column where I store the AVG of the rows and then I just take average of the temp table column. 我当时的想法是,我有一个带有单列的临时表,我在其中存储行的AVG,然后取临时表列的平均值。 Was just wondering if there might be a better way of doing it. 只是想知道是否可能有更好的方法。

I would use cross apply and grouping sets : 我将使用cross applygrouping sets

select t.id, avg(row_avg)
from t cross apply
     (select avg(col) as row_avg
      from (values (col1), (col2), (col3), (col4)) v(col)
     ) s
group by grouping sets ( (id), () );

The above assumes that you have a unique id to identify each row. 上面假设您有一个唯一的ID来标识每一行。 If not, then you need something like union all : 如果没有,那么您需要类似union all东西:

with s as (
      select t.*, s.row_avg
      from t cross apply
           (select avg(col) as row_avg
            from (values (col1), (col2), (col3), (col4)) v(col)
           ) s
     )
select s.row_avg
from s
union all
select avg(s.row_avg)
from s;

Try with CROSS APPLY 尝试使用CROSS APPLY

SELECT 
    AVG(t2.Average)
FROM
    Table t1
    CROSS APPLY (
        SELECT Average = AVG(Value) 
        FROM (VALUES (Col1), (Col2), (Col3), (Col4)) B1(Value)
    ) t2

Result is 65.221666 结果是65.221666

So you need both average for each row and each column? 因此,您需要每一行和每一列的平均值? I would do two separate calculations, one for row and another for column. 我将执行两个单独的计算,一个用于行,另一个用于列。 Read through the table and find the average for each row, store the column values in a temp column tables or lists. 通读表并找到每一行的平均值,将列值存储在临时列表或列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM