且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

具有CASE语句和SUM函数的LINQ查询

更新时间:2023-02-07 10:07:18

以下是使用Northwinds数据库的示例.这将为您提供预期的结果,但是SQL与您的示例不匹配.

Here is an example using the Northwinds database. This will get you the results that you are expecting but the SQL won't match your example.

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.Where(d => d.Order.OrderDate.Value <= volumn1Date)
                                  // cast to Int32? because if no records are found the result will be a null                                              
                                  .Sum(d => (Int32?) d.Quantity),
                    Volume7Day = g.Where(d => d.Order.OrderDate.Value <= volumn7Date)
                                  .Sum(d => (Int32?) d.Quantity),
                    Volume30Day = g.Where(d => d.Order.OrderDate.Value <= volumn30Date)
                                   .Sum(d => (Int32?) d.Quantity)
                };


    var list = query.ToList();
}