使用group by获取列的平均值

时间:2017-07-05 12:01:40

标签: c# linq

我试图根据其组来获取表格的平均值,

from avgtbl1 in table1
group avgtbl1 by new
{
    avgtbl1 .Prop1,
    avgtbl1 .Prop2,
    avgtbl1 .Prop3,
    avgtbl1 .Prop4
} into tempavgtbl1 
select new
{
    Prop1= tempavgtbl1 .Key.Prop1,
    Prop2= tempavgtbl1 .Key.Prop2,
    Prop3= tempavgtbl1 .Key.Prop3,
    Prop4= tempavgtbl1 .Key.Prop4,
    prop5= tempavgtbl1 .Average(a =>  a.Prop4)
};  

执行查询后,它给出了prop4的相同值,而不是prop4的基于prop1,prop2,prop3的平均值。我没有得到我错的地方。

 |Prop1 | prop2 |prop3| prop4|
 |1     | abc   |123  |    20|
 |1     | abc   |123  |    24|
 |2     | abc   |123  |    20|
 |2     | abc   |123  |    24|
 |3     | pqr   |  123|    27|
 |3     | pqr   |  123|    29|



 Expected Result

 |Prop1 | prop2 |prop3| prop4|prop5|
 |1     | abc   |123  |    20| 22  |
 |1     | abc   |123  |    24| 22  |
 |2     | abc   |123  |    21| 22.5|
 |2     | abc   |123  |    24| 22.5|
 |3     | pqr   |  123|    27| 28  |
 |3     | pqr   |  123|    29| 28  |

目前的结果:

 |Prop1 | prop2 |prop3| prop4|prop5|
 |1     | abc   |123  |    20|   20|
 |1     | abc   |123  |    24|   24|
 |2     | abc   |123  |    21|   21|
 |2     | abc   |123  |    24|   24|
 |3     | pqr   |  123|    27|   27|
 |3     | pqr   |  123|    29|   29|

1 个答案:

答案 0 :(得分:1)

问题在于您正在Prop4进行分组。要做你想做的事,你必须计算平均值,然后加入到原始表中以获得非平均值。此外,您只需将Prop4分组到其他列,这样就不必在Average中指定列。

from a1 in table1
group a1.Prop4 by new
{
    a1.Prop1,
    a1.Prop2,
    a1.Prop3
} into grp
join a2 in table1 
on grp.Key equals new {a2.Prop1, a2.Prop2, a2.Prop3};    
select new
{
    a2.Prop1, // or grp.Key.Prop1,
    a2.Prop2, // or grp.Key.Prop2,
    a2.Prop3, // or grp.Key.Prop3,
    a2.Prop4,
    Prop5 = grp.Average()
}

或者也可以使用子查询来完成。

from a1 in table1 
select new
{
    a1.Prop1, 
    a1.Prop2, 
    a1.Prop3, 
    a1.Prop4,
    Prop5 = (from a2 in table1
             where a2.Prop1 = a1.Prop1
                   && a2.Prop2 = a1.Prop2
                   && a2.Prop3 = a1.Prop3
             select a2.Prop4).Average()
}
相关问题