Linq to Sql for counting and averaging a dataset (without grouping)

I would like to execute the Linq to Sql statement, which captures the quantity and average value in a (filtered) dataset. I have work, but the database requires two queries, when it is possible in one query.

Interestingly, I can get one request that will be emitted when I use the group by clause.

For instance:

select count(*), avg(duration) from events

My linq looks like this:

var x = from e in db.events
        select e;
x = from i in x
    where i.NAME == "foo"
    select i;

return new {
    count = x.Count(),
    avgDuration = x.Average(e => e.Duration)
    };

With this code, I get two requests:

SELECT AVG([t0].[DURATION]) AS [value] FROM [dbo].[EVENTS] AS [t0]

and

SELECT COUNT(*) AS [value] FROM [dbo].[EVENTS] AS [t0]

Is there another way?

+3
source share
1 answer

The best I can get is a nested subquery:

var x = from e in db.events 
        group e by 1 into grp
        select new { 
            count = grp.Count(), 
            avgDuration = grp.Average(x => x.Duration) }

According to LINQPad, this will output SQL:

DECLARE @p0 Int = 1

SELECT COUNT(*) AS [count], AVG([t1].[Amount]) AS [avgDuration]
FROM (
    SELECT @p0 AS [value], [t0].[Duration]
    FROM Events AS [t0]
    ) AS [t1]
GROUP BY [t1].[value]
+7
source

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


All Articles