0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【データ基盤構築/BigQuery】少数点付きの数値の計算をする時は、NUMERIC型に変換してから計算しないと誤差が出てしまう

Last updated at Posted at 2022-12-27

今回の課題

BigQueryにて、離脱率や直帰率などの○○率数値の計算する際に、
INT64やFLOAT型のまま割り算をすると、正確の数値が出なかった。

理由は、BigQueryで少数点以下が発生する数値の計算をする際は、
NUMERIC型に変換して計算をしなければ、誤差が発生してしまうためだった。
(詳しくは、NUMERICの不思議参照)

解決策

少数点が発生する数値をNUMERICに変換したうえで、計算を行った。
これで正確な数値を算出できる。

select
    cast(exits as numeric) / cast(pageviews as numeric) as exits_rates -- 離脱数÷PV数=離脱率
    , cast(bounces as numeric) / cast(pagevies as numeric) as bounces_rates -- 直帰数÷PV数=直帰率
from
    `テーブル名`

また、〇〇率数値におかしな数値が無いか、ざっと確認しておくと尚良い。
シンプルに、0〜100%の間の数値になっているか確認するのでも良い。

例えば、下記のクエリでデータが抽出されない(COUNTの結果が0になる)ことを確認するなど行う。

with master as (
    select
        cast(exits as numeric) / cast(pageviews as numeric) as exits_rates-- 離脱数÷PV数=離脱率
        , cast(bounces as numeric) / cast(pagevies as numeric) as bounces_rates -- 直帰数÷PV数=直帰率
    from
        `テーブル名`
)
select
    count(*)
from
    master
where
    1=1
    and exits_rates < 0
    and exits_rates > 100
    and bounces_rates < 0
    and bounces_rates > 100

【参考】
(SQLite)Select句で計算をした場合に少数にする方法
[SQL]割合を計算するときの定石(割られる数をCASTする)
NUMERICの不思議

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?