`avg` of decimals truncates the result instead of rounding it

Open Beginner friendly
#27,688 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
62/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
rust, sql

Research direction

The truncation happens in DecimalAverager::avg in datafusion/functions-aggregate-common/src/utils.rs, where the scaled sum is divided by the count with div_wrapping. Reproduce with the SQL in the issue to confirm 1.666666 against the expected 1.666667, then change the division to round half away from zero. Done when avg(1, 2, 2) on decimal(10,2) returns 1.666667 and existing decimal aggregate tests still pass.

Written by the indexing model from the issue text.

Description

Describe the bug

avg over a decimal column returns Decimal(p + 4, s + 4) (MySQL's convention), but it computes the value by truncating, not rounding. DecimalAverager::avg scales the sum and then divides by the count with div_wrapping, which is integer division and truncates toward zero:

https://github.com/apache/datafusion/blob/dbb98dedc329a296a5153019b5ccfdf260088c3f/datafusion/functions-aggregate-common/src/utils.rs#L144-L146

So the last digit of an average is often one unit too small in magnitude.

To Reproduce

datafusion-cli 55.3.0:

select avg(x), arrow_typeof(avg(x))
from (values (cast(1 as decimal(10,2))), (cast(2 as decimal(10,2))), (cast(2 as decimal(10,2)))) as v(x);
-- 1.666666, Decimal128(14, 6)

The same average elsewhere:

avg(1, 2, 2)
DataFusion 55.3.0 1.666666
MySQL 8.4.13 (same result scale, 6) 1.666667
PostgreSQL 16 1.6666666666666667
Expected behavior

The average is rounded to the result scale, half away from zero, as MySQL (whose s + 4 scale this follows) and PostgreSQL do: 1.666667 here.

Additional context

Decimal / has the same issue in the arrow-rs division kernel, reported at https://github.com/apache/arrow-rs/issues/12426. This one is separate: the average is computed here, not through that kernel.

Dominant language
Rust
Stars
9.6k
Forks
2.7k
Avg merge
3d 17h
Merged PRs (30d)
318

Getting set up

Open in Codespaces

Starts the project's dev container in your browser, under your own GitHub account.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from apache/datafusion

All issues in apache/datafusion

Similar issues

More Rust issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.