andygrove opened a new issue, #27688:
URL: https://github.com/apache/datafusion/issues/27688

   ### 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:
   
   ```sql
   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.
   


-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to