efcore icon indicating copy to clipboard operation
efcore copied to clipboard

SqlServer Nested Aggregations - Invalid Sql

Open brenwebber opened this issue 6 years ago • 2 comments

I'm trying to perform a nested group by, but it is being converted to invalid Sql.

C# Linq query:

from projectStats in
  (from donation in this.context.Donations
    group donation by donation.ProjectId into donations
    select new
    {
      ProjectId = donations.Key,
      DonationCount = donations.Count(),
      Donated = donations.Sum(d => d.Donated),
    })
  group projectStats by 1 into allProjects
  select new
  {
    ProjectCount = allProjects.Count(),
    MostDonations = allProjects.Max(c => c.DonationCount),
    MaxDonated = allProjects.Max(c => c.Donated),
  }

Produces Sql:

SELECT COUNT(*) AS [ProjectCount], MAX(COUNT(*)) AS [MostDonations], MAX(COALESCE(SUM([d].[Donated]), 0.0)) AS [MaxDonated]
FROM [Donations] AS [d]
GROUP BY [d].[ProjectId]

And Error:

Microsoft.Data.SqlClient.SqlException : Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

Rather than pulling all projects back and aggregating in memory, I'd prefer to perform this aggregate in sql, but EF is refusing to nest the query. Is there any way to force it that I am not aware of? I have tried various versions of the above query, but no luck. Will revert to raw sql now.

Looking for Sql a bit more like this:

SELECT COUNT(*) AS ProjectCount, MAX(DonationCount) AS MostDonations, MAX(Donated) As MaxDonated
FROM
(
	SELECT ProjectId, COUNT(*) As DonationCount, SUM(Donated) As Donated
	FROM Donations aa
	GROUP BY ProjectId
) as projects

Sample project to replicate in Unit Test.

EFCoreSqlServerNestedGroupAggregate.zip

Version Info

EF Core version: 5.0.0 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET 5.0 Operating system: Win10 IDE: VS 2019 16.8.2

brenwebber avatar Nov 22 '20 19:11 brenwebber

@brenwebber as a work around, if you perform a join in the outer query it produces the correct sql:

from projectStats in
  (from donation in this.context.Donations
  group donation by donation.ProjectId into donations
  select new
  {
    ProjectId = donations.Key,
    DonationCount = donations.Count(),
    Donated = donations.Sum(d => d.Donated),
  })
join projects in this.context.Projects on projectStats.ProjectId equals projects.ProjectId
group projectStats by 1 into allProjects
select new
{
  ProjectCount = allProjects.Count(),
  MostDonations = allProjects.Max(c => c.DonationCount),
  MaxDonated = allProjects.Max(c => c.Donated),
}

brmza avatar Jan 08 '21 06:01 brmza

Thanks @brmza, I will give that a try.

brenwebber avatar Jan 18 '21 05:01 brenwebber