Linq to Sql用于计数和平均一组数据(无分组)

时间:2010-07-20 23:10:05

标签: c# linq-to-sql

我想执行一个Linq to Sql语句,该语句捕获(过滤的)数据集中的计数和平均值。我的工作原理,但在一个查询中应该可以对数据库进行两次查询。

有趣的是,当我使用group by子句时,我可以发出一个查询。

例如:

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

我的linq看起来像这样:

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)
    };

使用该代码我得到两个查询:

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

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

还有其他办法吗?

1 个答案:

答案 0 :(得分:7)

我能得到的最好的是嵌套子查询:

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

根据LINQPad,这将输出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]