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 3 years have passed since last update.

トランザクションデータのまとまりにIDを割り当てる

Last updated at Posted at 2021-03-11

概要

SQLでトランザクションデータを扱うとき、特定のルールに沿ったまとまりごとに処理を行いたい時がある。
自分で1から加工するのが結構大変だったので、備忘のために記事として残す。

やり方

1.扱いたいデータのまとまりの切り替わりのタイミングを定義し、UUIDを生成する
2.生成したUUIDをまとまりの中で割り当てる

例として、PVのトランザクションデータの中で、あるユーザが連続して同じ階層(page_category)をPVしたまとまりを取得したいときの例を以下に示す。
※BigQueryでの例
UUIDの生成やIDの振り分けは関数を用いており標準機能の範疇でないので、DBによって変える必要がある

連続するページカテゴリの回遊のまとまりを分類する
select
    *,
    case
        when unique_id is null then last_value(unique_id ignore nulls) over(
            partition by user_id
            order by pv_time rows unbounded preceding
        )
    end pv_chunk_id,
from (
    select
        *,
        case
            when page_category != lag(page_category, 1) over (
                partition by user_id
                order by pv_time
            ) then null
            else generate_uuid()
        end unique_id,
    from
        sample_pv_transaction
)

ここでは、ページ階層(page_category)が切り替わったタイミングでUUIDを生成しているが、この定義を変えることで色々なトランザクションのまとまりへの活用が効く。

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?