Lambda for Groupby and Sum?

本文关键字:Sum and Groupby for Lambda | 更新日期: 2023-09-27 18:11:56

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

这是我的查询,但我不知道如何按ProductName和Sum Sales Amount分组

Lambda for Groupby and Sum?

试试这个:

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

你根本不需要Join,因为你已经有了ProductKey,然后用来连接InternetSales表。

我认为你可以这样结束:

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