LINQ Query with both CASE statement and SUM function

前端 未结 2 1513
孤街浪徒
孤街浪徒 2021-01-21 06:28

I\'m struggling to find an example of how to return a conditional sum using a LINQ query or LAMBDA. I\'ve written both independently but combining the CASE with SUM is vexing.

2条回答
  •  攒了一身酷
    2021-01-21 07:22

    answer does not wrong but does not generate optimize query. better answer is:

    using (var context = new NorthwindEntities())
    {
        DateTime volumn1Date = DateTime.Today.AddDays(-1);
        DateTime volumn7Date = DateTime.Today.AddDays(-7);
        DateTime volumn30Date = DateTime.Today.AddDays(-30);
    
    var query = from o in context.Order_Details
                    group o by o.Product.ProductName into g
                    select new
                    {
                        ProductName = g.Key,
                        Volume1Day = g.Sum(d => d.Order.OrderDate.Value <= volumn1Date ? (Int32?) d.Quantity : 0),
                        Volume7Day = g.Sum(d => d.Order.OrderDate.Value <= volumn7Date ? (Int32?) d.Quantity : 0),
                        Volume30Day = g.Sum(d => d.Order.OrderDate.Value <= volumn30Date ? (Int32?) d.Quantity : 0)
                    };
    
        var list = query.ToList();
    }
    

提交回复
热议问题