Linq to Sql query with multiple aggregates

Given a simple circuit, for example. PurchaseOrders {OrderId, Total, LineItemCount}, I want to create a simple query for some simple characteristics, as shown below:

select sum(lineitemcount) as totalitems, sum(total) as totalsales
from purchaseorders

However, in Linq to Sql, I am trying to get this in a single query.

At the moment I have this:

decimal totalSales = PurchaseOrders.Sum(po => po.Total)
decimal totalItems = PurchaseOrders.Sum(po => po.LineItemcount)

Is there a way to do this as a single request?

+3
source share
3 answers

, group-by. , , SQL "1" , . , :

PurchaseOrders
    .GroupBy(po => 1)
    .Select(pogroup => new {
           TotalSales = pogroup.Sum(po => po.Total),
           TotalItems = pogroup.Sum(po => po.LineItemCount)
        });
+2

, . , , .

from t in (
    from t in PurchaseOrders
    select new {
        t.LineItemCount,
        t.Total,
        Dummy = "x"
    }
)
group t by new { t.Dummy } into g
select new {
  TotalItems = (System.Int32?)g.Sum(p => p.LineItemCount),
  TotalSales = (System.Int32?)g.Sum(p => p.Total)
}
+1

Perhaps you can try Aggregate:

var totOrder= PurchaseOrders.Aggregate((preOrder, thisOrder)=>SumTwoOrder(preOrder, thisOrder));
var totalSales = totOrder.Total;
var totalItems=totOrder.LineItemCount;

Here is how you can define a method SumTwoOrder:

   public PurchaseOrder SumTwoOrder(PurchaseOrder prev, PurchaseOrder thisOrder)
  {
    return new PurchaseORder(prev.Total+thisOrder.Total, prev.LineItemCount+thisOrder.LineItemCount);
  }
+1
source

Source: https://habr.com/ru/post/1725269/


All Articles