Description

Hey guys,

after having spent a couple of hours figuring out why a subquery annotated with Count fails, I came to the conclusion that Count in a query causes GROUP BY clauses added to it, which in turn renders the SQL subquery useless.

Please investigate this example which I just added to Stack Overflow as a resolution, and see what I'm talking about:

Change History (4)

It's not clear to me why you not expecting a GROUP BY statement to be present in the subquery when you are explicitly grouping by id by using values('id') before annotating. Please see the section about aggregation and the usage of values() to GROUP BY in the ​aggregation documentation.

It's not clear to me why you not expecting a GROUP BY statement to be present in the subquery when you are explicitly grouping by id by using values('id') before annotating. Please see the section about aggregation and the usage of values() to GROUP BY in the

The reason for why I needed to get rid of the GROUP BY clause was because it broke the COUNT() on the SQL level. I recognized this after going down to the SQL level and fiddling around with native SQL queries to find out why I'm getting NULL values at the counts. So here's a simplified version how the clause with GROUP BY looks, and what results it brings, copying from the MariaDB command line:

See, it's returning proper values now. So that is why I went back to the ORM level and played around with it until I managed to remove the GROUP BY clause from the subquery. Basically, empirical testing.

Also it's worth mentioning that when I managed to remove the GROUP BY on the ORM level, executing the query without specifying the output field resulted in an exception when evaluating the query the first time, but not the second time:

It would require to either make aggregate return a lazy object that Subquery can deal with (right now it returns a dict on call) which has the potential of breaking backward compatibility or introducing a new kind of expression to deal with this case (e.g. AggregateSubquery(query, Count('pk'))).

In an ideal world we'd be able to call count() directly and avoid the Subquery wrapper

I'm converting the ticket to a feature request for subquery aggregation. It has a bit of overlap with #10060 as it would add a way to work around the issue by explicitly using subqueries as opposed to having the ORM do automatic pushdown but I still consider this a feature on it's own.