2017-07-05 57 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() 
}