.net - 单个Linq-to-Entities查询中的多个SQL聚合函数

标签 .net entity-framework linq-to-entities

在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/

相关文章:

entity-framework - Linq 到实体和 Xml 字段

entity-framework-4 - 无法使用 LINQ to Entities 和 LinqKit/PredicateBuilder 进行重构

c# - 我正在构建的应用程序是否可以使用现有的数据层?

c# - 创建要应用于 IQueryable 的动态搜索的最简单方法

sql - 关于 Entity Framework 的思考

c# - 使用 include Entity Framework core 3.1 时如何过滤嵌套对象

c# - 无法将匿名类型从 'System.Linq.IQueryable' 转换为 'System.Data.Entity.Core.Objects.ObjectQuery'

c# - 使用不安全将指向 CLR 类型的指针分配给 void*?

c# - 在 ASP.NET 中将 Eval 与 ImageURL 绑定(bind)

c# - 为什么 $ 不总是匹配到行尾