Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to Sql query with multiple aggregations

Given a simple schema e.g. PurchaseOrders { OrderId, Total, LineItemCount }, I want to generate a simple query for some simple stats like below:

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

However in Linq to Sql I am struggling to get this into one 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 one query?

like image 226
amarsuperstar Avatar asked Feb 15 '26 22:02

amarsuperstar


2 Answers

Closest I can work out is to give it a fake group-by clause. It works, and outputs as you'd expect, but the generated SQL actually winds up passing in a parameter of "1" and grouping on it which is a tad suboptimal. Here's the syntax for what I've got though:

PurchaseOrders
    .GroupBy(po => 1)
    .Select(pogroup => new {
           TotalSales = pogroup.Sum(po => po.Total),
           TotalItems = pogroup.Sum(po => po.LineItemCount)
        });
like image 161
fyjham Avatar answered Feb 18 '26 11:02

fyjham


Maybe you can try Aggregate:

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

This is how you can define the SumTwoOrder method:

   public PurchaseOrder SumTwoOrder(PurchaseOrder prev, PurchaseOrder thisOrder)
  {
    return new PurchaseORder(prev.Total+thisOrder.Total, prev.LineItemCount+thisOrder.LineItemCount);
  }
like image 42
Graviton Avatar answered Feb 18 '26 11:02

Graviton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!