Multiple aggregate functions in one query using Linq to SQL [duplicate]

谁说胖子不能爱 提交于 2019-12-02 19:19:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!