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】UNION結合とGROUPBYを併用する際に、視認性が高いクエリの書き方

Posted at

今回の課題

ひとつのクエリ内で、UNIONとGROUPBYを使用した際に、
視認性が低くなってしまった。

そのため、視認性の高いクエリの書き方をメモすることにした。

視認性の高いクエリ

下記の手順でクエリを記述すると視認性が高くなった。

  1. WITH句内でUNION結合。
  2. 外側のクエリでGROUP BYする
with master as (
    select
        session
        , user_id
        , case
            when user_id is null then 'guest'
            when user_id is not null then 'login'
            else null
		end as login_status
        , action
        , category
        , products
        , amount
        , stamp
    from
        action_log
	union all
    select
        session
        , user_id
        , 'all' as login_status
        , action
        , category
        , products
        , amount
        , stamp
	from
        action_log
)
select
    action
    , login_status
    , count(session) as action_count
    , count(distinct session) as action_uu
from
    master
group by
    action
    , login_status
;

視認性の低いクエリ

最初はこちらでクエリを作成してしまった。
GROUPBYしながらUNION結合していたため、非常に見づらいクエリになってしまっていた。

with master as (
    select
        action
        , case
            when user_id is null then 'guest'
            when user_id is not null then 'login'
            else null
		end as login_status
        , count(session) as action_count
        , count(distinct session) as action_uu
    from
        action_log
    group by
        actoin
        , login_staus
	union all
    select
        action
        , 'all' as login_status
        , count(session) as action_count
        , count(distinct session) as action_uu
	from
        action_log
    group by
        action
)
select
    *
from
    master
;
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?