开发者

LINQ to SQL: orderby a sum operation

I have a table where I need order a result set by sum a numeric column according to a group by clause.

For example, the table has a salesperson ID, order number, and 开发者_Go百科order value. I want a top 10 list of my top salespeople by accumulated order value.

New to SQL and LINQ, so any advice would be appreciated!


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


Something like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜