LINQ查询同时包含CASE语句和SUM函数

时间:2010-12-30 13:16:33

标签: c# linq linq-to-sql sum case

我很难找到如何使用LINQ查询或LAMBDA返回条件和的示例。我已经独立写了两篇,但将CASE和SUM结合起来很令人烦恼。我很想“欺骗”并使用SQL视图,但我想先问一下。我非常感谢任何建议。这是我想要转换的SQL。

SELECT     p.product_name, 
           SUM(CASE WHEN o.order_dt <= getdate() - 1 THEN o.quantity END) AS volume_1day, 
           SUM(CASE WHEN o.order_dt <= getdate() - 7 THEN o.quantity END) AS volume_7day, 
           SUM(CASE WHEN o.order_dt <= getdate() - 30 THEN o.quantity END) AS volume_30day, 
           SUM(o.quantity) AS volume_all
FROM       products p left outer join orders o on p.product_id = o.product_id
GROUP BY   p.product_name

2 个答案:

答案 0 :(得分:4)

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

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();
}

答案 1 :(得分:3)

答案没有错,但不会生成优化查询。更好的答案是:

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();
}