在日期之间获得十大最畅销产品

时间:2013-01-12 00:41:21

标签: c# .net linq

我想在用户指定的日期内退回最畅销的十大产品(数量最多)。

我的数据库表格:

订单

OrderId | OrderDate

Order_Products

ProductID | OrderID | Quantity

产品

ProductID | ProductName | ProductDescription

代码:

return (from product in this.Entities.Products
        from orderProduct in this.Entities.Order_Product 
        from order in this.Entities.Orders
        where order.OrderId = orderProduct.ProductID && orderProduct.ProductID == product.ProductID
        where (order.OrderDate >= date1 &&  <= date2)
        select product).OrderByAscending(COUNT(Quantity)).Distinct().Take(10);

到目前为止的代码。

2 个答案:

答案 0 :(得分:1)

我可以想到两种方法来做到这一点

这会对每个产品进行子查询,以总结日期范围之间的销售数量。这对我来说似乎最清楚,但可能表现不佳

  var query = 
   (from p in Entities.Products
    let totalQuantity = ( from op in Entities.Order_Product
                          join o in Entities.Orders on op.OrderID equals o.OrderId
                          where op.ProductID == p.ProductID && o.OrderDate >= date1 && o.OrderDate <= date2
                          select op.Quantity ).Sum()
    where totalQuantity > 0
    orderby totalQuantity descending
    select p).Take(10);

或者作为获取日期范围内所有订单的单个查询,按产品对其进行分组,然后对数量求和。

  var query = 
   (from p in Entities.Products
    join op in Entities.Order_Product on p.ProductID equals op.ProductID
    join o in Entities.Orders on op.OrderID equals o.OrderId
    where o.OrderDate >= date1 && o.OrderDate <= date2
    select new { Product = p, Quantity = op.Quantity } into productQty
    group productQty by productQty.Product into pg
    let totalQuantity = pg.Sum(prod => prod.Quantity)
    orderby totalQuantity descending
    select pg.Key).Take(10);

答案 1 :(得分:0)

var query = 
   (from p in Entities.Products
    join op in Entities.Order_Product on p.ProductID equals op.ProductID
    join o in Entities.Orders on op.OrderID equals o.OrderId
    where o.OrderDate >= date1 && o.OrderDate <= date2
    select new { Product = p, op.Quantity } into pq
    group pq by pq.Product.ProductID into g
    select g.OrderByDescending(x => x.Quantity).First().Product).Take(10);