You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "Jefffrey (via GitHub)" <gi...@apache.org> on 2025/08/20 05:11:35 UTC
[PR] Support `avg(distinct)` for `float64` type [datafusion]
Jefffrey opened a new pull request, #17255:
URL: https://github.com/apache/datafusion/pull/17255
## Which issue does this PR close?
<!--
We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
-->
Relates to #2408
- Decimal support not included so can't close issue yet
## Rationale for this change
<!--
Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
-->
Building on old PR #15413, to get it over the line. Opened as new PR as other PR was too old and wasn't sure if should push to the original author branch; for now pushed to my own branch but preserved the original commits.
## What changes are included in this PR?
<!--
There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
-->
From original PR:
1. mv `DistinctSumAccumulator` to common so that it can be used in `Float64DistinctAvgAccumulator`
2. implement `Float64DistinctAvgAccumulator` using `DistinctSumAccumulator`
3. tested in `aggregate.slt`
Additional changes made by me:
- Fixed error `query error DataFusion error: Arrow error: Invalid argument error: number of columns\(1\) must match number of fields\(2\) in schema` (https://github.com/apache/datafusion/pull/15413#issuecomment-2779088360) which was caused by wrong state fields
- Update the SLT test cases (removed the decimal test cases as those aren't relevant for this float PR)
## Are these changes tested?
<!--
We typically require tests for all PRs in order to:
1. Prevent the code from being accidentally broken by subsequent changes
2. Serve as another way to document the expected behavior of the code
If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
-->
Added SLT tests, and also regenerated the extended tests (TODO: link PR)
## Are there any user-facing changes?
<!--
If there are user-facing changes then we may require documentation to be updated before approving the PR.
-->
<!--
If there are any breaking changes to public APIs, please add the `api change` label.
-->
TODO: need to check if we explicitly documented about `avg(distinct)` in SQL documentation?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey merged PR #17255:
URL: https://github.com/apache/datafusion/pull/17255
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on PR #17255:
URL: https://github.com/apache/datafusion/pull/17255#issuecomment-3216228535
> This will I assume require regenerating the extended slt files in datafusion-testing?
Yep, refer to https://github.com/apache/datafusion-testing/pull/11
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #17255:
URL: https://github.com/apache/datafusion/pull/17255#discussion_r2295810676
##########
datafusion/sqllogictest/test_files/aggregate.slt:
##########
@@ -7387,3 +7389,59 @@ FROM (VALUES ('a'), ('d'), ('c'), ('a')) t(a_varchar);
query error Error during planning: ORDER BY and WITHIN GROUP clauses cannot be used together in the same aggregate function
SELECT array_agg(a_varchar order by a_varchar) WITHIN GROUP (ORDER BY a_varchar)
FROM (VALUES ('a'), ('d'), ('c'), ('a')) t(a_varchar);
+
+# distinct average
Review Comment:
❤️
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #17255:
URL: https://github.com/apache/datafusion/pull/17255#discussion_r2287004655
##########
datafusion/functions-aggregate/src/average.rs:
##########
@@ -114,72 +115,88 @@ impl AggregateUDFImpl for Avg {
}
fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
- if acc_args.is_distinct {
- return exec_err!("avg(DISTINCT) aggregations are not available");
- }
+ let data_type = acc_args.exprs[0].data_type(acc_args.schema)?;
use DataType::*;
- let data_type = acc_args.exprs[0].data_type(acc_args.schema)?;
// instantiate specialized accumulator based for the type
- match (&data_type, acc_args.return_field.data_type()) {
- (Float64, Float64) => Ok(Box::<AvgAccumulator>::default()),
- (
- Decimal128(sum_precision, sum_scale),
- Decimal128(target_precision, target_scale),
- ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal128Type> {
- sum: None,
- count: 0,
- sum_scale: *sum_scale,
- sum_precision: *sum_precision,
- target_precision: *target_precision,
- target_scale: *target_scale,
- })),
-
- (
- Decimal256(sum_precision, sum_scale),
- Decimal256(target_precision, target_scale),
- ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal256Type> {
- sum: None,
- count: 0,
- sum_scale: *sum_scale,
- sum_precision: *sum_precision,
- target_precision: *target_precision,
- target_scale: *target_scale,
- })),
-
- (Duration(time_unit), Duration(result_unit)) => {
- Ok(Box::new(DurationAvgAccumulator {
+ if acc_args.is_distinct {
+ match &data_type {
+ // Numeric types are converted to Float64 via `coerce_avg_type` during logical plan creation
+ Float64 => Ok(Box::new(Float64DistinctAvgAccumulator::default())),
+ _ => exec_err!("AVG(DISTINCT) for {} not supported", data_type),
+ }
+ } else {
+ match (&data_type, acc_args.return_field.data_type()) {
+ (Float64, Float64) => Ok(Box::<AvgAccumulator>::default()),
+ (
+ Decimal128(sum_precision, sum_scale),
+ Decimal128(target_precision, target_scale),
+ ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal128Type> {
sum: None,
count: 0,
- time_unit: *time_unit,
- result_unit: *result_unit,
- }))
- }
+ sum_scale: *sum_scale,
+ sum_precision: *sum_precision,
+ target_precision: *target_precision,
+ target_scale: *target_scale,
+ })),
+
+ (
+ Decimal256(sum_precision, sum_scale),
+ Decimal256(target_precision, target_scale),
+ ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal256Type> {
+ sum: None,
+ count: 0,
+ sum_scale: *sum_scale,
+ sum_precision: *sum_precision,
+ target_precision: *target_precision,
+ target_scale: *target_scale,
+ })),
+
+ (Duration(time_unit), Duration(result_unit)) => {
+ Ok(Box::new(DurationAvgAccumulator {
+ sum: None,
+ count: 0,
+ time_unit: *time_unit,
+ result_unit: *result_unit,
+ }))
+ }
- _ => exec_err!(
- "AvgAccumulator for ({} --> {})",
- &data_type,
- acc_args.return_field.data_type()
- ),
+ _ => exec_err!(
+ "AvgAccumulator for ({} --> {})",
+ &data_type,
+ acc_args.return_field.data_type()
+ ),
+ }
}
}
fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
- Ok(vec![
- Field::new(
- format_state_name(args.name, "count"),
- DataType::UInt64,
- true,
- ),
- Field::new(
- format_state_name(args.name, "sum"),
- args.input_fields[0].data_type().clone(),
- true,
- ),
- ]
- .into_iter()
- .map(Arc::new)
- .collect())
+ if args.is_distinct {
+ // Copied from datafusion_functions_aggregate::sum::Sum::state_fields
+ // since the accumulator uses DistinctSumAccumulator internally.
+ Ok(vec![Field::new_list(
+ format_state_name(args.name, "sum distinct"),
+ Field::new_list_field(args.return_type().clone(), true),
+ false,
+ )
+ .into()])
+ } else {
+ Ok(vec![
+ Field::new(
+ format_state_name(args.name, "count"),
+ DataType::UInt64,
+ true,
+ ),
+ Field::new(
+ format_state_name(args.name, "sum"),
+ args.input_fields[0].data_type().clone(),
+ true,
+ ),
+ ]
+ .into_iter()
+ .map(Arc::new)
+ .collect())
+ }
Review Comment:
This is my main contribution in addition to the changes from the original PR, to fix that error with the differing field counts. I wonder if there's a better way to architect this, since wasn't clearly obvious that this is related to the state of the accumulator
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #17255:
URL: https://github.com/apache/datafusion/pull/17255#discussion_r2295094117
##########
datafusion/sqllogictest/test_files/aggregate.slt:
##########
@@ -7387,3 +7389,58 @@ FROM (VALUES ('a'), ('d'), ('c'), ('a')) t(a_varchar);
query error Error during planning: ORDER BY and WITHIN GROUP clauses cannot be used together in the same aggregate function
SELECT array_agg(a_varchar order by a_varchar) WITHIN GROUP (ORDER BY a_varchar)
FROM (VALUES ('a'), ('d'), ('c'), ('a')) t(a_varchar);
+
+# distinct average
+statement ok
+create table distinct_avg (a int, b int) as values
+ (null, null),
+ (1, 1),
+ (2, 2),
+ (3, 3),
+ (4, 4),
Review Comment:
Will work on adding these cases 👍
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #17255:
URL: https://github.com/apache/datafusion/pull/17255#discussion_r2287475500
##########
datafusion/functions-aggregate/src/average.rs:
##########
@@ -114,79 +115,95 @@ impl AggregateUDFImpl for Avg {
}
fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
- if acc_args.is_distinct {
- return exec_err!("avg(DISTINCT) aggregations are not available");
- }
+ let data_type = acc_args.exprs[0].data_type(acc_args.schema)?;
use DataType::*;
- let data_type = acc_args.exprs[0].data_type(acc_args.schema)?;
// instantiate specialized accumulator based for the type
- match (&data_type, acc_args.return_field.data_type()) {
- (Float64, Float64) => Ok(Box::<AvgAccumulator>::default()),
- (
- Decimal128(sum_precision, sum_scale),
- Decimal128(target_precision, target_scale),
- ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal128Type> {
- sum: None,
- count: 0,
- sum_scale: *sum_scale,
- sum_precision: *sum_precision,
- target_precision: *target_precision,
- target_scale: *target_scale,
- })),
-
- (
- Decimal256(sum_precision, sum_scale),
- Decimal256(target_precision, target_scale),
- ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal256Type> {
- sum: None,
- count: 0,
- sum_scale: *sum_scale,
- sum_precision: *sum_precision,
- target_precision: *target_precision,
- target_scale: *target_scale,
- })),
-
- (Duration(time_unit), Duration(result_unit)) => {
- Ok(Box::new(DurationAvgAccumulator {
+ if acc_args.is_distinct {
+ match &data_type {
+ // Numeric types are converted to Float64 via `coerce_avg_type` during logical plan creation
+ Float64 => Ok(Box::new(Float64DistinctAvgAccumulator::default())),
+ _ => exec_err!("AVG(DISTINCT) for {} not supported", data_type),
+ }
+ } else {
+ match (&data_type, acc_args.return_field.data_type()) {
+ (Float64, Float64) => Ok(Box::<AvgAccumulator>::default()),
+ (
+ Decimal128(sum_precision, sum_scale),
+ Decimal128(target_precision, target_scale),
+ ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal128Type> {
sum: None,
count: 0,
- time_unit: *time_unit,
- result_unit: *result_unit,
- }))
- }
+ sum_scale: *sum_scale,
+ sum_precision: *sum_precision,
+ target_precision: *target_precision,
+ target_scale: *target_scale,
+ })),
+
+ (
+ Decimal256(sum_precision, sum_scale),
+ Decimal256(target_precision, target_scale),
+ ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal256Type> {
+ sum: None,
+ count: 0,
+ sum_scale: *sum_scale,
+ sum_precision: *sum_precision,
+ target_precision: *target_precision,
+ target_scale: *target_scale,
+ })),
+
+ (Duration(time_unit), Duration(result_unit)) => {
+ Ok(Box::new(DurationAvgAccumulator {
+ sum: None,
+ count: 0,
+ time_unit: *time_unit,
+ result_unit: *result_unit,
+ }))
+ }
- _ => exec_err!(
- "AvgAccumulator for ({} --> {})",
- &data_type,
- acc_args.return_field.data_type()
- ),
+ _ => exec_err!(
+ "AvgAccumulator for ({} --> {})",
+ &data_type,
+ acc_args.return_field.data_type()
+ ),
+ }
}
}
fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
- Ok(vec![
- Field::new(
- format_state_name(args.name, "count"),
- DataType::UInt64,
- true,
- ),
- Field::new(
- format_state_name(args.name, "sum"),
- args.input_fields[0].data_type().clone(),
- true,
- ),
- ]
- .into_iter()
- .map(Arc::new)
- .collect())
+ if args.is_distinct {
+ // Copied from datafusion_functions_aggregate::sum::Sum::state_fields
+ // since the accumulator uses DistinctSumAccumulator internally.
+ Ok(vec![Field::new_list(
+ format_state_name(args.name, "sum distinct"),
+ Field::new_list_field(args.return_type().clone(), true),
+ false,
+ )
+ .into()])
+ } else {
+ Ok(vec![
+ Field::new(
+ format_state_name(args.name, "count"),
+ DataType::UInt64,
+ true,
+ ),
+ Field::new(
+ format_state_name(args.name, "sum"),
+ args.input_fields[0].data_type().clone(),
+ true,
+ ),
+ ]
+ .into_iter()
+ .map(Arc::new)
+ .collect())
+ }
}
fn groups_accumulator_supported(&self, args: AccumulatorArgs) -> bool {
matches!(
args.return_field.data_type(),
DataType::Float64 | DataType::Decimal128(_, _) | DataType::Duration(_)
- )
+ ) && !args.is_distinct
Review Comment:
Similar to how sum handles it:
https://github.com/apache/datafusion/blob/8c58f532a1ed29dc8b8d70b87ee33a4745325e8f/datafusion/functions-aggregate/src/sum.rs#L223-L225
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #17255:
URL: https://github.com/apache/datafusion/pull/17255#discussion_r2295094013
##########
datafusion/functions-aggregate/src/average.rs:
##########
@@ -114,72 +115,88 @@ impl AggregateUDFImpl for Avg {
}
fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
- if acc_args.is_distinct {
- return exec_err!("avg(DISTINCT) aggregations are not available");
- }
+ let data_type = acc_args.exprs[0].data_type(acc_args.schema)?;
use DataType::*;
- let data_type = acc_args.exprs[0].data_type(acc_args.schema)?;
// instantiate specialized accumulator based for the type
- match (&data_type, acc_args.return_field.data_type()) {
- (Float64, Float64) => Ok(Box::<AvgAccumulator>::default()),
- (
- Decimal128(sum_precision, sum_scale),
- Decimal128(target_precision, target_scale),
- ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal128Type> {
- sum: None,
- count: 0,
- sum_scale: *sum_scale,
- sum_precision: *sum_precision,
- target_precision: *target_precision,
- target_scale: *target_scale,
- })),
-
- (
- Decimal256(sum_precision, sum_scale),
- Decimal256(target_precision, target_scale),
- ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal256Type> {
- sum: None,
- count: 0,
- sum_scale: *sum_scale,
- sum_precision: *sum_precision,
- target_precision: *target_precision,
- target_scale: *target_scale,
- })),
-
- (Duration(time_unit), Duration(result_unit)) => {
- Ok(Box::new(DurationAvgAccumulator {
+ if acc_args.is_distinct {
+ match &data_type {
+ // Numeric types are converted to Float64 via `coerce_avg_type` during logical plan creation
+ Float64 => Ok(Box::new(Float64DistinctAvgAccumulator::default())),
+ _ => exec_err!("AVG(DISTINCT) for {} not supported", data_type),
+ }
+ } else {
+ match (&data_type, acc_args.return_field.data_type()) {
+ (Float64, Float64) => Ok(Box::<AvgAccumulator>::default()),
+ (
+ Decimal128(sum_precision, sum_scale),
+ Decimal128(target_precision, target_scale),
+ ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal128Type> {
sum: None,
count: 0,
- time_unit: *time_unit,
- result_unit: *result_unit,
- }))
- }
+ sum_scale: *sum_scale,
+ sum_precision: *sum_precision,
+ target_precision: *target_precision,
+ target_scale: *target_scale,
+ })),
+
+ (
+ Decimal256(sum_precision, sum_scale),
+ Decimal256(target_precision, target_scale),
+ ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal256Type> {
+ sum: None,
+ count: 0,
+ sum_scale: *sum_scale,
+ sum_precision: *sum_precision,
+ target_precision: *target_precision,
+ target_scale: *target_scale,
+ })),
+
+ (Duration(time_unit), Duration(result_unit)) => {
+ Ok(Box::new(DurationAvgAccumulator {
+ sum: None,
+ count: 0,
+ time_unit: *time_unit,
+ result_unit: *result_unit,
+ }))
+ }
- _ => exec_err!(
- "AvgAccumulator for ({} --> {})",
- &data_type,
- acc_args.return_field.data_type()
- ),
+ _ => exec_err!(
+ "AvgAccumulator for ({} --> {})",
+ &data_type,
+ acc_args.return_field.data_type()
+ ),
+ }
}
}
fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
- Ok(vec![
- Field::new(
- format_state_name(args.name, "count"),
- DataType::UInt64,
- true,
- ),
- Field::new(
- format_state_name(args.name, "sum"),
- args.input_fields[0].data_type().clone(),
- true,
- ),
- ]
- .into_iter()
- .map(Arc::new)
- .collect())
+ if args.is_distinct {
+ // Copied from datafusion_functions_aggregate::sum::Sum::state_fields
+ // since the accumulator uses DistinctSumAccumulator internally.
+ Ok(vec![Field::new_list(
+ format_state_name(args.name, "sum distinct"),
+ Field::new_list_field(args.return_type().clone(), true),
+ false,
+ )
+ .into()])
+ } else {
+ Ok(vec![
+ Field::new(
+ format_state_name(args.name, "count"),
+ DataType::UInt64,
+ true,
+ ),
+ Field::new(
+ format_state_name(args.name, "sum"),
+ args.input_fields[0].data_type().clone(),
+ true,
+ ),
+ ]
+ .into_iter()
+ .map(Arc::new)
+ .collect())
+ }
Review Comment:
Sorry, what I meant was that in accumulators we can return the `state()` like so:
https://github.com/apache/datafusion/blob/be3842b55d61095d77aae54426726ddd1eed5f2c/datafusion/functions-aggregate/src/sum.rs#L432-L450
However this must align with `state_fields()` of the parent aggregate UDF:
https://github.com/apache/datafusion/blob/be3842b55d61095d77aae54426726ddd1eed5f2c/datafusion/functions-aggregate/src/sum.rs#L204-L221
But this isn't clearly obvious at compile time, and during runtime we only hit this issue for certain test cases (for this distinct avg PR). So I was wondering if there was a better way to enforce this at compile time. Hope that clears it up.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #17255:
URL: https://github.com/apache/datafusion/pull/17255#discussion_r2294598360
##########
datafusion/sqllogictest/test_files/aggregate.slt:
##########
@@ -7387,3 +7389,58 @@ FROM (VALUES ('a'), ('d'), ('c'), ('a')) t(a_varchar);
query error Error during planning: ORDER BY and WITHIN GROUP clauses cannot be used together in the same aggregate function
SELECT array_agg(a_varchar order by a_varchar) WITHIN GROUP (ORDER BY a_varchar)
FROM (VALUES ('a'), ('d'), ('c'), ('a')) t(a_varchar);
+
+# distinct average
+statement ok
+create table distinct_avg (a int, b int) as values
+ (null, null),
+ (1, 1),
+ (2, 2),
+ (3, 3),
+ (4, 4),
Review Comment:
Could you update this test so:
1. The input isn't in order
2. Add a test for floating point values
3. Test for an input that includes at least one null value
4. the values in `b` are different than the values in `b`
##########
datafusion/functions-aggregate/src/average.rs:
##########
@@ -114,79 +115,95 @@ impl AggregateUDFImpl for Avg {
}
fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
- if acc_args.is_distinct {
- return exec_err!("avg(DISTINCT) aggregations are not available");
- }
+ let data_type = acc_args.exprs[0].data_type(acc_args.schema)?;
use DataType::*;
- let data_type = acc_args.exprs[0].data_type(acc_args.schema)?;
// instantiate specialized accumulator based for the type
- match (&data_type, acc_args.return_field.data_type()) {
- (Float64, Float64) => Ok(Box::<AvgAccumulator>::default()),
- (
- Decimal128(sum_precision, sum_scale),
- Decimal128(target_precision, target_scale),
- ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal128Type> {
- sum: None,
- count: 0,
- sum_scale: *sum_scale,
- sum_precision: *sum_precision,
- target_precision: *target_precision,
- target_scale: *target_scale,
- })),
-
- (
- Decimal256(sum_precision, sum_scale),
- Decimal256(target_precision, target_scale),
- ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal256Type> {
- sum: None,
- count: 0,
- sum_scale: *sum_scale,
- sum_precision: *sum_precision,
- target_precision: *target_precision,
- target_scale: *target_scale,
- })),
-
- (Duration(time_unit), Duration(result_unit)) => {
- Ok(Box::new(DurationAvgAccumulator {
+ if acc_args.is_distinct {
+ match &data_type {
+ // Numeric types are converted to Float64 via `coerce_avg_type` during logical plan creation
+ Float64 => Ok(Box::new(Float64DistinctAvgAccumulator::default())),
+ _ => exec_err!("AVG(DISTINCT) for {} not supported", data_type),
+ }
+ } else {
+ match (&data_type, acc_args.return_field.data_type()) {
+ (Float64, Float64) => Ok(Box::<AvgAccumulator>::default()),
+ (
+ Decimal128(sum_precision, sum_scale),
+ Decimal128(target_precision, target_scale),
+ ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal128Type> {
sum: None,
count: 0,
- time_unit: *time_unit,
- result_unit: *result_unit,
- }))
- }
+ sum_scale: *sum_scale,
+ sum_precision: *sum_precision,
+ target_precision: *target_precision,
+ target_scale: *target_scale,
+ })),
+
+ (
+ Decimal256(sum_precision, sum_scale),
+ Decimal256(target_precision, target_scale),
+ ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal256Type> {
+ sum: None,
+ count: 0,
+ sum_scale: *sum_scale,
+ sum_precision: *sum_precision,
+ target_precision: *target_precision,
+ target_scale: *target_scale,
+ })),
+
+ (Duration(time_unit), Duration(result_unit)) => {
+ Ok(Box::new(DurationAvgAccumulator {
+ sum: None,
+ count: 0,
+ time_unit: *time_unit,
+ result_unit: *result_unit,
+ }))
+ }
- _ => exec_err!(
- "AvgAccumulator for ({} --> {})",
- &data_type,
- acc_args.return_field.data_type()
- ),
+ _ => exec_err!(
+ "AvgAccumulator for ({} --> {})",
+ &data_type,
+ acc_args.return_field.data_type()
+ ),
+ }
}
}
fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
- Ok(vec![
- Field::new(
- format_state_name(args.name, "count"),
- DataType::UInt64,
- true,
- ),
- Field::new(
- format_state_name(args.name, "sum"),
- args.input_fields[0].data_type().clone(),
- true,
- ),
- ]
- .into_iter()
- .map(Arc::new)
- .collect())
+ if args.is_distinct {
+ // Copied from datafusion_functions_aggregate::sum::Sum::state_fields
+ // since the accumulator uses DistinctSumAccumulator internally.
+ Ok(vec![Field::new_list(
+ format_state_name(args.name, "sum distinct"),
Review Comment:
```suggestion
format_state_name(args.name, "avg distinct"),
```
##########
datafusion/functions-aggregate/src/average.rs:
##########
@@ -114,72 +115,88 @@ impl AggregateUDFImpl for Avg {
}
fn accumulator(&self, acc_args: AccumulatorArgs) -> Result<Box<dyn Accumulator>> {
- if acc_args.is_distinct {
- return exec_err!("avg(DISTINCT) aggregations are not available");
- }
+ let data_type = acc_args.exprs[0].data_type(acc_args.schema)?;
use DataType::*;
- let data_type = acc_args.exprs[0].data_type(acc_args.schema)?;
// instantiate specialized accumulator based for the type
- match (&data_type, acc_args.return_field.data_type()) {
- (Float64, Float64) => Ok(Box::<AvgAccumulator>::default()),
- (
- Decimal128(sum_precision, sum_scale),
- Decimal128(target_precision, target_scale),
- ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal128Type> {
- sum: None,
- count: 0,
- sum_scale: *sum_scale,
- sum_precision: *sum_precision,
- target_precision: *target_precision,
- target_scale: *target_scale,
- })),
-
- (
- Decimal256(sum_precision, sum_scale),
- Decimal256(target_precision, target_scale),
- ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal256Type> {
- sum: None,
- count: 0,
- sum_scale: *sum_scale,
- sum_precision: *sum_precision,
- target_precision: *target_precision,
- target_scale: *target_scale,
- })),
-
- (Duration(time_unit), Duration(result_unit)) => {
- Ok(Box::new(DurationAvgAccumulator {
+ if acc_args.is_distinct {
+ match &data_type {
+ // Numeric types are converted to Float64 via `coerce_avg_type` during logical plan creation
+ Float64 => Ok(Box::new(Float64DistinctAvgAccumulator::default())),
+ _ => exec_err!("AVG(DISTINCT) for {} not supported", data_type),
+ }
+ } else {
+ match (&data_type, acc_args.return_field.data_type()) {
+ (Float64, Float64) => Ok(Box::<AvgAccumulator>::default()),
+ (
+ Decimal128(sum_precision, sum_scale),
+ Decimal128(target_precision, target_scale),
+ ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal128Type> {
sum: None,
count: 0,
- time_unit: *time_unit,
- result_unit: *result_unit,
- }))
- }
+ sum_scale: *sum_scale,
+ sum_precision: *sum_precision,
+ target_precision: *target_precision,
+ target_scale: *target_scale,
+ })),
+
+ (
+ Decimal256(sum_precision, sum_scale),
+ Decimal256(target_precision, target_scale),
+ ) => Ok(Box::new(DecimalAvgAccumulator::<Decimal256Type> {
+ sum: None,
+ count: 0,
+ sum_scale: *sum_scale,
+ sum_precision: *sum_precision,
+ target_precision: *target_precision,
+ target_scale: *target_scale,
+ })),
+
+ (Duration(time_unit), Duration(result_unit)) => {
+ Ok(Box::new(DurationAvgAccumulator {
+ sum: None,
+ count: 0,
+ time_unit: *time_unit,
+ result_unit: *result_unit,
+ }))
+ }
- _ => exec_err!(
- "AvgAccumulator for ({} --> {})",
- &data_type,
- acc_args.return_field.data_type()
- ),
+ _ => exec_err!(
+ "AvgAccumulator for ({} --> {})",
+ &data_type,
+ acc_args.return_field.data_type()
+ ),
+ }
}
}
fn state_fields(&self, args: StateFieldsArgs) -> Result<Vec<FieldRef>> {
- Ok(vec![
- Field::new(
- format_state_name(args.name, "count"),
- DataType::UInt64,
- true,
- ),
- Field::new(
- format_state_name(args.name, "sum"),
- args.input_fields[0].data_type().clone(),
- true,
- ),
- ]
- .into_iter()
- .map(Arc::new)
- .collect())
+ if args.is_distinct {
+ // Copied from datafusion_functions_aggregate::sum::Sum::state_fields
+ // since the accumulator uses DistinctSumAccumulator internally.
+ Ok(vec![Field::new_list(
+ format_state_name(args.name, "sum distinct"),
+ Field::new_list_field(args.return_type().clone(), true),
+ false,
+ )
+ .into()])
+ } else {
+ Ok(vec![
+ Field::new(
+ format_state_name(args.name, "count"),
+ DataType::UInt64,
+ true,
+ ),
+ Field::new(
+ format_state_name(args.name, "sum"),
+ args.input_fields[0].data_type().clone(),
+ true,
+ ),
+ ]
+ .into_iter()
+ .map(Arc::new)
+ .collect())
+ }
Review Comment:
I don't really understand this question -- the PR's code looks good to me
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on PR #17255:
URL: https://github.com/apache/datafusion/pull/17255#issuecomment-3204604429
Looks like still getting same error for some of the extended tests:
```
# Datafusion - Datafusion expected results:
query error DataFusion error: Arrow error: Invalid argument error: number of columns\(5\) must match number of fields\(4\) in schema
SELECT ALL - AVG ( ALL + col0 ) AS col1 FROM tab0 GROUP BY col0 HAVING + AVG ( DISTINCT - col2 ) IS NULL
```
Will look into this
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #17255:
URL: https://github.com/apache/datafusion/pull/17255#issuecomment-3218005743
🚀
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #17255:
URL: https://github.com/apache/datafusion/pull/17255#issuecomment-3216735334
I think all we need now is to merge https://github.com/apache/datafusion-testing/pull/11 and then update the `datafusion-testing` pin on this PR.
I am testing locally with the changes from https://github.com/apache/datafusion-testing/pull/11 using:
```shell
INCLUDE_SQLITE=true cargo test --profile release-nonlto --test sqllogictests
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #17255:
URL: https://github.com/apache/datafusion/pull/17255#discussion_r2295610306
##########
datafusion/sqllogictest/test_files/aggregate.slt:
##########
@@ -7387,3 +7389,58 @@ FROM (VALUES ('a'), ('d'), ('c'), ('a')) t(a_varchar);
query error Error during planning: ORDER BY and WITHIN GROUP clauses cannot be used together in the same aggregate function
SELECT array_agg(a_varchar order by a_varchar) WITHIN GROUP (ORDER BY a_varchar)
FROM (VALUES ('a'), ('d'), ('c'), ('a')) t(a_varchar);
+
+# distinct average
+statement ok
+create table distinct_avg (a int, b int) as values
+ (null, null),
+ (1, 1),
+ (2, 2),
+ (3, 3),
+ (4, 4),
Review Comment:
Addressed those points in this commit: https://github.com/apache/datafusion/pull/17255/commits/3abb4b729b87c80a6c6083caf2c68f221d97b96c
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #17255:
URL: https://github.com/apache/datafusion/pull/17255#issuecomment-3216745731
```\ Finished `release-nonlto` profile [optimized] target(s) in 2m 09s
Running bin/sqllogictests.rs (target/release-nonlto/deps/sqllogictests-78c77c9b80ab3916)
Completed 942 test files in 4 minutes
andrewlamb@Andrews-MacBook-Pro-3:~/Software/datafusion$
```
👍
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on PR #17255:
URL: https://github.com/apache/datafusion/pull/17255#issuecomment-3216761513
> I updated the pin and merged up from main
Cheers 👍
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #17255:
URL: https://github.com/apache/datafusion/pull/17255#issuecomment-3216751873
I updated the pin and merged up from main
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "Omega359 (via GitHub)" <gi...@apache.org>.
Omega359 commented on PR #17255:
URL: https://github.com/apache/datafusion/pull/17255#issuecomment-3215422900
This will I assume require regenerating the extended slt files in datafusion-testing?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org
Re: [PR] Support `avg(distinct)` for `float64` type [datafusion]
Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on PR #17255:
URL: https://github.com/apache/datafusion/pull/17255#issuecomment-3205232658
> Looks like still getting same error for some of the extended tests:
>
> ```
> # Datafusion - Datafusion expected results:
> query error DataFusion error: Arrow error: Invalid argument error: number of columns\(5\) must match number of fields\(4\) in schema
> SELECT ALL - AVG ( ALL + col0 ) AS col1 FROM tab0 GROUP BY col0 HAVING + AVG ( DISTINCT - col2 ) IS NULL
> ```
>
> Will look into this
>
> Edit: seems to be related to group accumulator support
Fixed by https://github.com/apache/datafusion/pull/17255/commits/bc121fbf46639bc6dde7791658cb2f624fc3ea8c
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org