LINQ to SQL:通过求和操作排序

时间:2011-06-12 00:09:37

标签: linq sum operations

我有一个表格,我需要根据group by子句通过数字列对结果集进行排序。

例如,该表具有销售员ID,订单号和订单值。我希望按累计订单价值列出我的顶级销售人员的前10名。

SQL和LINQ的新手,所以任何建议都会受到赞赏!

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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();