【问题标题】:Linq group by in sum column from with where clauseLinq group by in sum column from with where 子句
【发布时间】:2017-12-15 04:17:26
【问题描述】:
public class PowerPlantsBudgetUsage
    {
         public int  PowerPlantID { get; set; }
   public int TotalWork { get; set; }
    public int ElectricalWorkNo { get; set; }
    public int MechanicalWorkNo { get; set; }
    public int CivilWorkNo { get; set; }
    public int AdminWorkNo { get; set; }
    public int VehicleWorkNo { get; set; }
    [DisplayFormat(DataFormatString = "{0:N}")] 
    public decimal ElectricalBudgetOnly { get; set; }
    public decimal Total { get; set; }
    public string PowerPlantName { get; set; }
    }

 public IActionResult Total()
        {
             var query = _context.REHPData.Include(r => r.PowerPlants).Include(r => r.WorkCategories).GroupBy(r => r.PowerPlantID).Select(s => new PowerPlantsBudgetUsage
        {
            PowerPlantID = s.Key,
            PowerPlantName = s.Select(p => p.PowerPlants.PowerPlantName).First(),
            TotalWork = s.Count(),
            ElectricalWorkNo = s.Count(x => x.WorkCategoriesID == 1),
            MechanicalWorkNo = s.Count(x => x.WorkCategoriesID == 2),
            CivilWorkNo = s.Count(x => x.WorkCategoriesID == 3),
            AdminWorkNo = s.Count(x => x.WorkCategoriesID == 4),
            VehicleWorkNo = s.Count(x => x.WorkCategoriesID == 6),
            Total = s.Sum(x => x.ApprovedAmount),
            ElectricalBudgetOnly = s.Sum(x => x.ApprovedAmount).Where(x=>x.WorkCategoriesID==1) /*this column result is s.Sum(x => x.ApprovedAmount).Where(WorkCategoriesID == 1)  */

        }).ToList();
        return View(query);

        }

我的问题是 ElectricalBudgetOnly 是 ApprovedAmount 的总和,其中 CategoriesID == 1 powrplantname 是 test test test test test 以此类推...

【问题讨论】:

    标签: entity-framework linq


    【解决方案1】:

    你的错误是你把它交换了。

    //...
    ElectricalBudgetOnly = s.Where(x => x.WorkCategoriesID == 1).Sum(x => x.ApprovedAmount)
    

    先应用 where 再对 where 的结果求和

    【讨论】:

    猜你喜欢
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 2012-12-08
    相关资源
    最近更新 更多