编写一个LINQ查询以按产品类别查询每个销售员的总销售额

问题描述

我正在尝试编写一个LINQ查询,以使用northwind数据库根据产品类别查找每个员工的总销售额。

所需结果应为:

EmployeeID:ProductCategoryID:totalNumberofSales

例如:

1stemployee:第一类:x销售 。 。

nthEmployee:nthCategory:y销售

northWind数据库中的表是员工,订单,订单明细,产品,类别。

我尝试过此方法,但最后还是卡住了。

    List<ORDER_DETAILS> o_details = db.ORDER_DETAILS.ToList();
                    List<ORDERS> orders = db.ORDERS.ToList();
                    List<CATEGORIES> categories = db.CATEGORIES.ToList();
                    List<EMPLOYEES> employee = db.EMPLOYEES.ToList();
                    List<PRODUCTS> products= db.PRODUCTS.ToList();
    
                    var list= orders.GroupJoin(employee,o => o.PersonelID,e => e.PersonelID,(e,os) => new { e,os.})
.GroupJoin(o_details,tp => tp.e.OrderID,od => od.OrderID,(od,tps) => new { od,tps })
.GroupJoin(products,tp2 => tp2.od.e.ORDER_DETAILS,p => p.ORDER_DETAILS,(tp2,ps) => new{tp2,ps})
.GroupJoin(categories,tp3=>tp3.ps,c=>c.CategoryID,(tp3s,cs)=>new { tp3s,cs}).GroupBy(m => new {  }

解决方法

您的罗斯文(Northwind)数据库可能与我的数据库不同,因为我没有PersonelID列,但是有EmployeeID,但希望这会有所帮助。

如果不是为了打折,则可以简单地将orderDetails记录分组,即

 var summary = (from od in OrderDetails
 group od by new { od.Order.EmployeeID,od.Product.CategoryID } into results
 orderby results.Key.EmployeeID,results.Key.CategoryID 
 select new
 {
    results.Key.EmployeeID,results.Key.CategoryID,Sales = results.Sum(a => a.UnitPrice * a.Quantity)
 } 
 ).ToList();

由于四舍五入等问题,折扣使它更加复杂,但是您可以使用提供了ExtendedPrice列的OrderDetailsExtended视图,但是这意味着您需要执行显式联接而不是导航属性,例如

 var summary2 = (from od in OrderDetailsExtended 
    join order   in Orders   on od.OrderID   equals order.OrderID
    join product in Products on od.ProductID equals product.ProductID
    group od by new { order.EmployeeID,product.CategoryID } into results
    orderby results.Key.EmployeeID,results.Key.CategoryID
    select new
    {
        results.Key.EmployeeID,Sales = results.Sum(a => a.ExtendedPrice)
    }
    ).ToList();