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

オープン 初心者向け
#27,688 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
2/5
見積もり時間
1〜3時間
初心者へのやさしさ
62/100
issue の種類
バグ
明瞭さ
明確に書かれている
活発さ
活発
技術スタック
rust, sql

調査の方向性

切り捨ては datafusion/functions-aggregate-common/src/utils.rs の DecimalAverager::avg で発生しており、スケール済みの合計を div_wrapping で件数で割っている箇所です。issue の SQL で再現し、期待値 1.666667 に対して 1.666666 となることを確認したうえで、除算を0から遠ざかる方向への半分切り上げ(round half away from zero)に変更してください。avg(1, 2, 2) を decimal(10,2) に対して実行すると 1.666667 が返り、既存の decimal 集計テストがすべて通れば完了です。

索引モデルが issue の本文から書いたものです。

説明

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.

主要言語
Rust
スター
9.6k
フォーク
2.7k
平均マージ
3日 17時間
マージ済み PR(30日)
318

環境構築

Codespaces で開く

このプロジェクトの開発コンテナを、あなたの GitHub アカウントでブラウザ上に起動します。

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

apache/datafusion のほかの issue

apache/datafusion の issue をすべて見る

似ている issue

Rust の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。