Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SUM and COUNT in single LINQ to SQL query

I'm trying to create the following query in LINQ-TO-SQL.

select count(*), sum( o.CostInCents ) from Orders o
where Flag = true;

I came up with the following LINQ query:

var q = db.Orders
    .Where(o => o.Flag )

var result = q
    .GroupBy(o => 1)
    .Select(g => new MyDTO
    {
        NoOfOrders = g.Count(),
        TotalInCents = g.Sum(o => o.CostInCents )
    })
    .SingleOrDefaultAsync();

Is there a better way?

Is .GroupBy(o => 1) even OK?

The other option would be to do two queries, like below.

var q = db.Orders
   .Where(o => o.Flag );

//No groupBy
var result2 = new MyDTO
{
    NoOfCostedOrders = q.Count(),//hit the db
    TotalInCents = q.Sum(o => o.CostInCents )//hit the db 2nd time
};

How should I judge which approach is better?

Thanks in advance!

like image 837
tymtam Avatar asked Oct 07 '16 07:10

tymtam


2 Answers

This query can be rewritten in sql format as follows

var orderList = db.Orders.Where(o => o.Flag );
var orderSummary = from o in orderList
                   group o by 1 into p
                   select new
                   {
                      Items = p.Count(),
                      Total = p.Sum( x => x.CostInCents)
                   }
like image 108
Uttam Kar Avatar answered Sep 20 '22 17:09

Uttam Kar


I think what you are searching for is the following slight adjustment:

var q = db.Orders
   .Where(o => o.Flag).Select(o => o.CostInCents).ToList(); // hit the db here once

//No groupBy
var result2 = new MyDTO
{
    NoOfCostedOrders = q.Count(), // don't hit the db
    TotalInCents = q.Sum() // don't hit the db a 2nd time
};

If you have a question to my adjustment feel free to comment.

like image 38
jonzbonz Avatar answered Sep 16 '22 17:09

jonzbonz