LINQ to Entities 中的加权平均值

问题描述 投票:0回答:1

请考虑此表:

重量:

City          Weight
--------------------
Tokyo          100
München        150
Köln           200

和数据:

ID       Country       City           Value
--------------------------------------------
1        Germany       München        10
2        Germany       München        20
3        Japan         Tokyo          12
4        Japan         Tokyo          20
5        Japan         Tokyo          8
6        Germany       Köln           5 
7        Germany       Köln           7
8        Germany       Köln           9

我想计算每个国家的加权平均值:

我写了这个查询:

var MyResult = (from d in MyContext.Data
                join w in MyContext.Weight
                on d.City equals w.City
                select new {
                   d.Country,
                   d.City,
                   d.Value,
                   w.Weight
                }).GroupBy(p=>new {p.Country})
                  .Select(o=>new
                             {
                                 o.Key.Country,
                                 WeightedAverage = o.Sum(k=>k.Value * k.Weight) / o.Sum(k=>k.Weight)
                             })

但它为我返回了错误的加权平均值。我想计算这个公式:

对于德国:

(10 * 150 + 20 * 150 + 5 * 200 + 7 * 200 + 9 * 200) / (150 + 200)

怎样才能达到我想要的结果?

谢谢

c# sql-server entity-framework linq linq-to-entities
1个回答
0
投票

我不太确定 EF 也可以翻译这个,但是写评论太长了,所以我将其作为答案发布。试试这个:

var MyResult = (from d in MyContext.Data
                join w in MyContext.Weight
                on d.City equals w.City
                select new {
                   d.Country,
                   d.City,
                   d.Value,
                   w.Weight
                }).GroupBy(p=>new {p.Country})
                  .Select(o=>new
                             {
                                 o.Key.Country,
                                 WeightedAverage = o.Sum(k=>k.Value * k.Weight) / 
       MyContext.Weight.Where(w=> o.Select(q=> q.City).Contains(w.City))
                       .Select(w=> w.Weight))).Sum()
                             })
© www.soinside.com 2019 - 2024. All rights reserved.