Linq其他类别年销售额百分比总和超过100%

时间:2016-09-18 08:42:50

标签: c# entity-framework linq

我有一个linq查询,用于计算按年份和国家/地区划分的销售额总和。一切正常,除非将总销售额不足2%的国家纳入“其他”类别

我的代码:

using (var context = new ChinookContext())
{
  var rawset = context.Invoices.Include(l => l.InvoiceLines)
    .GroupBy(i => new { i.BillingCountry, i.InvoiceDate.Year })
    .Select(f => new
    {
      Country = f.Key.BillingCountry,
      Year = f.Key.Year,
      TotalSales = f.Sum(l => l.InvoiceLines.Sum(t => t.Quantity * t.UnitPrice))
    })
    .ToList();

  var result = rawset
    .Select(r => new {
    GrandTotal = rawset.Sum(t => t.TotalSales),
    CountryTotal =
      rawset.GroupBy(c => c.Country)
      .Select(p => new
      {
        CountryKey = p.Key,
        CountryTotalSales = p.Sum(t => t.TotalSales)
      }),
      Member = r})
      .Select(f => new
      {
        Country = (
          f.CountryTotal
          .Where(c => c.CountryKey == f.Member.Country)
          .Select(x => x.CountryTotalSales).SingleOrDefault()
          / f.GrandTotal > 0.02M)
          ? f.Member.Country : "Others",
          Year = f.Member.Year,
          YearlySales = f.Member.TotalSales,
          TotalSalesByCountry = f.CountryTotal
            .Where(c => c.CountryKey == f.Member.Country)
            .Select(c => c.CountryTotalSales).FirstOrDefault(),
          GrandTotal = f.GrandTotal
      })
      .ToList();

  var finalresult = result.GroupBy(r => new { r.Country, r.Year })
    .Select(final => new
    {
      Country = final.Key.Country,
      Year = final.Key.Year,
      YearlySales = final.Sum(y => y.YearlySales),
      PercentageByCountry = final.Sum(y => y.YearlySales)
        / final.Sum(c => c.TotalSalesByCountry)
        * 100,
      PercentageByGrandTotal = final.Sum(y => y.YearlySales)
        / final.Select(x => x.GrandTotal).FirstOrDefault()
        * 100
  })
  .OrderBy(f => f.Country)
  .ThenBy(f => f.Year);
}

问题是每个国家/地区的年度销售占该国家总销售额的百分比。

除了“其他”类别超过100%外,其他所有国家都运作良好。

非常感谢任何建议。

提前致谢。

1 个答案:

答案 0 :(得分:1)

在计算TotalSalesByCountry时,您不会考虑“其他”案例,即当它低于2%时。因此,在“其他”国家

的情况下执行PercentageByCountry = final.Sum(y => y.YearlySales) / final.Sum(c => c.TotalSalesByCountry) * 100时,计算会出错