Skip to content

fix: round the avg of decimals instead of truncating it - #27786

Open
abp002 wants to merge 1 commit into
apache:mainfrom
abp002:avg-decimal-round
Open

abp002 wants to merge 1 commit into
apache:mainfrom
abp002:avg-decimal-round

Conversation

@abp002

@abp002 abp002 commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Which issue does this PR close?

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:

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.

@github-actions github-actions Bot added sqllogictest SQL Logic Tests (.slt) functions Changes to functions implementation labels Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

functions Changes to functions implementation sqllogictest SQL Logic Tests (.slt)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

avg of decimals truncates the result instead of rounding it

1 participant