2011-06-12 75 views
3

我有一張表,我需要根據group by子句求和一個數字列來對結果集進行排序。LINQ to SQL:orderby sum操作

例如,該表具有銷售員ID,訂單號和訂單值。我希望通過累計訂單價值獲得排名前10的銷售人員名單。

新的SQL和LINQ,所以任何意見將不勝感激!

回答

7
var results = context.Sales.GroupBy(s => s.SalesPersonID) 
          .Select(g => new { 
               SalesPersonID = g.Key, 
               Sales = g.Sum(s => s.OrderValue) 
              }) 
          .OrderByDescending(r => r.Sales) 
          .Take(10); 
2

事情是這樣的:

var orders = new[] 
{ 
    new Order { SalesPersonId = 1, OrderNumber = 1, OrderValue = 1 }, 
    new Order { SalesPersonId = 1, OrderNumber = 2, OrderValue = 2 }, 
    new Order { SalesPersonId = 2, OrderNumber = 2, OrderValue = 2 }, 
}; 

var topSalesMen = orders 
    .GroupBy(arg => arg.SalesPersonId) 
    .Select(arg => new { SalesPersonId = arg.Key, TotalOrderValue = arg.Sum(x => x.OrderValue) }) 
    .OrderByDescending(arg => arg.TotalOrderValue) 
    .Take(10) 
    .ToList();