问题
I'm trying to achieve the following in LINQ (EF6):
SELECT count(A), sum(B), average(C)
FROM TableA,
LEFT JOIN TableB ON ...
LEFT JOIN TableC ON ...
WHERE
(very complicated conditions)
The C# code looks like following:
IQueryable<Entity> = dbSet
.Include(e => e.entityB)
.Include(e => e.EntityC)
.Where( <very complicated conditions> );
How can I apply multiple aggregate functions on different fields? Specifically, in a way, which won't cause the complicated conditions to be copied over and over in resulting query?
回答1:
You can use the group by constant trick to get all the aggregates with single SQL query (and shared complicated filter):
var result = dbSet
.Where( <very complicated conditions> )
.GroupBy(e => 1) // aribitrary value
.Select(g => new
{
CountA = g.Count(),
SumB = g.Sum(e => e.EntityB.PropertyB),
AverageC = g.Average(e => e.EntityC.PropertyC),
})
.FirstOrDefault();
来源:https://stackoverflow.com/questions/45144034/multiple-aggregate-functions-in-one-query-using-linq-to-sql