Consider making a relational SqlAggregateFunctionExpression with FILTER/DISTINCT/ORDER BY
- Dominant language
- C#
- Stars
- 14.8k
- Forks
- 3.4k
- PR merge metrics
- PR metrics pending
Description
Our query pipeline supports adding filter, distinct and order by clauses on aggregate functions. However, providers must currently create their own SQL expression types to take advantage of this, and generate the SQL from them (e.g. [SqlServerAggregateFunctionExpression](https://github.com/dotnet/efcore/blob/main/src/EFCore.SqlServer/Query/Internal/SqlServerAggregateFunctionExpression.cs), similar for PostgreSQL).
Upon investigation, it seems that most relational databases support at least some of these clauses - so we could have a relational SqlAggregateFunctionExpression with them. This would also create a clear distinction between regular and aggregate functions in the query tree, making it easier to pattern-match in certain cases (e.g. [window functions](https://github.com/dotnet/efcore/issues/12747)):
* The SQL:2003 FILTER clause is directly supported by [PostgreSQL](https://www.postgresql.org/docs/current/tutorial-agg.html) and [SQLite](https://sqlite.org/lang_aggfunc.html) (see [this great database comparison](https://modern-sql.com/feature/filter)).
* Where not supported, we can easily emulate via CASE/WHEN. So we could have a post-processing visitor that transforms FILTER to CASE/WHEN for universal support.
* DISTINCT and ORDER BY are more widely supported - PostgreSQL, [SQLite](https://sqlite.org/lang_aggfunc.html), SQL Server ([ordering](https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=azure-sqldw-latest) - notice non-standard syntax, [distinct](https://learn.microsoft.com/en-us/sql/t-sql/functions/avg-transact-sql?view=azure-sqldw-latest)), [MySQL](https://dev.mysql.com/doc/refman/8.4/en/aggregate-functions.html) and MariaDB, [Oracle DISTINCT](https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/Aggregate-Functions.html), [Firebird DISTINCT](https://www.firebirdsql.org/file/documentation/chunk/en/refdocs/fblangref30/fblangref30-aggfuncs.html#:~:text=Aggregate%20functions%20operate%20on%20groups%20of%20records,%20rather,See%20Window%20(Analytical)%20Functions%20for%20more%20information.%209.1.).
Contributor guide
Assessment
This issue has not been assessed yet.