LoginSignup
7
2

More than 1 year has passed since last update.

Hiveでランダムサンプリング

Last updated at Posted at 2017-04-14

概要

SQLライクな言語Hiveでのランダムサンプリングです。

以下のようなデータが続くとき
3行のみランダムに抽出したい

使用するデータ

customer_ID item_name date
 3 A   2016-10-11  
 3 B   2016-11-11  
 5 C   2016-12-10 
 2 A   2016-09-20  
 3 D   2016-08-09 

クエリ

SELECT 
    sample.customer_ID,
    sample.item_name,
    sample.date,
    sample.row_num

FROM

    (
    SELECT
          *, 
          --全行にランダムに行番号をふる
          row_number()             
              over(ORDER BY rand() ) as row_num          
    FROM        
          table
    ) as sample

WHERE
    --ランダムに振られた番号の1~3まで抽出
    sample.row_num between 1 and 3

イメージ

①全行にランダムに番号をふって(一番右の列)、

customer_ID item_name date row_num
 3 A   2016-10-11   1
 3 B   2016-11-11   5
 5 C   2016-12-10  3
 2 A   2016-09-20   4
 3 D   2016-08-09  2

②行番号が1-3のものだけ抽出

customer_ID item_name date row_num
 3 A   2016-10-11   1
 3 B   2016-11-11   5
 5 C  2016-12-10  3
 2 A   2016-09-20   4
 3 D   2016-08-09  2

③完成!

customer_ID item_name date row_num
 3 A   2016-10-11   1
 5 C 2016-12-10  3
 3 D   2016-08-09  2
7
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
7
2