在SQL中,您可以在单个数据库查询中表示多个聚合,如下所示:
SELECT MIN(p.x), MAX(p.x), MIN(p.y), MAX(p.y)
FROM Places p JOIN Logs l on p.Id = l.PlaceId
WHERE l.OwnerId = @OwnerId
是否可以使用Linq-to-Entities做等效的事情?我发现了一个similar question,这表明Linq-to-SQL是不可能的,但我想我不必使用四次往返数据库的操作来完成上述操作。
最佳答案
假设您具有以下SQL语句:
select sum(A), max(B), avg(C) from TBL group by D
在C#中尝试:
from t in table
group t by D
into g
select new {
s = g.Sum(x => x.A),
m = g.Max(x => x.B),
a = g.Average(x => x.C)
}
-或在VB中:-
from t in TBL
group t by key = D
into g = group
select s = g.Sum(function(x) x.A),
m = g.Max(function(x) x.B),
a = g.Average(function(x) x.C)
显而易见,在VB中将是:
aggregate t in TBL into s = Sum(t.A), m = Max(t.B), a = Average(t.C)
尽管它会给出相同的结果,但它会发出多个SQL select语句,每个语句针对一个聚合函数,因此成本较高,即它将多次运行。第一种语法给出了一个(相当复杂但有效)的SQL语句,该语句对数据库进行了一次传递。
PS。如果您没有用于分组的键(即结果需要一行,覆盖整个数据集),请使用以下常量:
from t in TBL
group t by key = 0
into g = group
select s = g.Sum(function(x) x.A),
m = g.Max(function(x) x.B),
a = g.Average(function(x) x.C)
关于.net - 单个Linq-to-Entities查询中的多个SQL聚合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4431781/