1
2

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で最頻値(mode, top)を集計する方法

Last updated at Posted at 2020-06-23

この記事は?

下記のようにユーザが訪問した都道府県が並んでいるテーブルがあったとします。
image.png

分析の都合上、ユーザごとにどこの都道府県にいったのかを1:1で対応させたいとします。
その際、ユーザが最も多く行った都道府県を選択するのが合理的な場合があります。

この記事はそのような集計のさいに最頻値を取り出す方法について説明します。

解決方法

下記のようにAPPROX_TOP_COUNT(x,n)関数を使用します。

SELECT
user_id 
, APPROX_TOP_COUNT(shop_loc,1)[OFFSET(0)].value shop_loc
FROM
tbl
GROUP BY user_id

参考

BigQuery公式

--下記のSQLを自分のプロジェクトで実行すると再現できます。
WITH tbl AS(
SELECT "A" AS user_id, 'tokyo'  as shop_loc, 1 visit_num
UNION ALL
SELECT "A" AS user_id, 'tokyo' as shop_loc, 2 visit_num
UNION ALL
SELECT "A" AS user_id, 'osaka' as shop_loc, 3 visit_num
UNION ALL
SELECT "A" AS user_id, null as shop_loc, 4 visit_num
UNION ALL
SELECT "B" AS user_id, 'kyoto' as shop_loc, 1 visit_num
)

SELECT
user_id 
, APPROX_TOP_COUNT(shop_loc,1)[OFFSET(0)].value shop_loc
FROM
tbl
GROUP BY 1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?