abp002 opened a new pull request, #27786:
URL: https://github.com/apache/datafusion/pull/27786

   ## Which issue does this PR close?
   
   - Closes #27688.
   
   ## Rationale for this change
   
   `avg` over a decimal column returns `Decimal(p + 4, s + 4)`, but the last 
digit is truncated instead of rounded. `avg` of `1.00`, `2.00` and `2.00` 
returns `1.666666`, where MySQL (same result scale) returns `1.666667`.
   
   ## What changes are included in this PR?
   
   `DecimalAverager::avg` rounds the quotient half away from zero, using the 
remainder of the division. `avg`, `avg(DISTINCT)`, the grouped accumulator and 
window frames all go through it, so they all round now.
   
   The rounding costs one more integer division per output value (per group, or 
per row of a window), not per input row.
   
   ## What is the testing strategy for this PR?
   
   Cases in `aggregate.slt` for the plain, grouped, distinct and window paths, 
with both signs, `Decimal256` and an exact tie (1 / 32). Unit tests for 
`DecimalAverager` cover the tie boundaries and a result that rounds past the 
precision, which SQL does not reach. All of them fail without the fix.
   
   Existing expected values that change in the last digit: two in `decimal.slt` 
and four in the TPC-H `q1` answers (`avg_qty` and `avg_disc`).
   
   ## Are there any user-facing changes?
   
   Yes. The last digit of a decimal `avg` can be one unit larger in magnitude 
than before:
   
   ```sql
   select 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);
   -- before: 1.666666
   -- after:  1.666667
   ```
   
   `avg` over a decimal with a negative scale still panics (#24898). That is 
not changed here.
   


-- 
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