2017-07-05 58 views
1

我想基于其组从表中获取的财产平均,获取使用组列平均通过

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

确定编辑样本数据的问题 – Pavan

+1

您应该只根据Prop1,Prop2和Prop3进行分组。您在Prop4中有不同的值,这使得行是唯一的,并且按组不会按预期工作。 –

回答

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