Lambby for Groupby和Sum?

时间:2013-05-01 20:24:15

标签: c# sql asp.net-mvc entity-framework lambda

var product = db.Products
                .Where(x => x.ProductKey == 310)
                .Join(db.InternetSales, p => p.ProductKey,
                       c => c.ProductKey, (p, c) => c)
                .SingleOrDefault();

这是我的查询,但我不知道如何按产品名称和销售额总和对其进行分组。

2 个答案:

答案 0 :(得分:0)

试试这个:

 var product = db.Products.Where(x => x.ProductKey == 310)
                 .Join(db.InternetSales, p => p.ProductKey, 
                       c => c.ProductKey, (p, c) => c)
                 .GroupBy(c => c.ProductName)
                 .Select(g => new { g.Key, TotalSales = g.Sum(x => x.Sales) })
                 .SingleOrDefault();

或者,如果需要总和,请尝试:

 var totalSales = db.Products.Where(x => x.ProductKey == 310)
                    .Join(db.InternetSales, p => p.ProductKey, 
                          c => c.ProductKey, (p, c) => c)
                    .GroupBy(c => c.ProductName)
                    .SingleOrDefault()
                    .Sum(x => x.Sales);

答案 1 :(得分:0)

您根本不需要Join,因为您已经拥有ProductKey,然后用于加入InternetSales表。

我认为你最终可以得到以下内容:

var TotalSales = db.InternetSales
                   .Where(s => s.ProductKey == 310)
                   .Select(s => s.Sales)
                   .Sum();