Snowflake でのデータ操作
Jake Roach
Field Data Engineer
サブクエリは、あるクエリの結果を別のクエリで利用できるようにする手法です。
$$
$$
FROM ( ... ) や WHERE ... IN ( ... ) で使用

SELECT
...
-- テーブルではなくクエリ結果から取得
FROM (
-- メインクエリで使う結果セットを作成
SELECT
<fields>
FROM <table>
WHERE ...
);
テーブルから直接ではなく、他のクエリ結果からデータを取得します。
$$
JOIN、WHERE などでも利用可SELECT
month_num,
-- ここでは windchill - temperature を2回使用。変更時にどうする?
AVG(windchill - temperature) AS avg_differential
MIN(windchill - temperature) AS most_differential
FROM weather
WHERE
-- 集計/分析と同じクエリでフィルタしている
season = 'Winter' AND
temperature < 32
GROUP BY month_num;
-- まずサブクエリを作り、次に集計SELECT month_num, AVG(differential) AS avg_differential MIN(differential) AS most_differential FROM (SELECT month_num, windchill - temperature AS differential FROM weather WHERE season = 'Winter' AND temperature < 32) GROUP BY month_num;
| month_num | differential |
| --------- | ------------ |
| 12 | -12 |
| 1 | -3 |
| 1 | 0 |
| 2 | -7 |
| month_num | avg_differential | most_differential |
| --------- | ---------------- | ----------------- |
| 12 | -5.77 | -14 |
| 1 | -1.91 | -8 |
| 2 | -8.13 | -22 |
データを整えた後は、分析の理解・変更が容易です。
...
-- サブクエリの結果に含まれる値でフィルタ
WHERE <field> IN (
SELECT <other-field> FROM ...
);
変換・フィルタ・操作に使う小さな結果セットを作成します。
$$
IN で抽出AVG, MAX, MIN などSELECT
todays_date,
temperature,
status
FROM weather
WHERE todays_date IN ( -- 勝利したホーム戦の日付でフィルタ
SELECT
game_date
FROM game_schedule
WHERE stadium = 'Home' AND did_win = TRUE
);

Snowflake でのデータ操作