子查詢

Snowflake 中的資料操作

Jake Roach

Field Data Engineer

什麼是子查詢?

子查詢可讓一個查詢的結果供另一個查詢使用。

$$

  • 結合多個查詢
  • 強化可讀性
  • 提升模組化
  • 更容易處理資料!

$$

FROM ( ... )WHERE ... IN ( ... )

以更可讀、模組化方式用子查詢操作資料的邏輯流程

Snowflake 中的資料操作

子查詢與 FROM

SELECT
    ...
-- Pull from query, not from a table
FROM (

    -- Create a result set that will 
    -- be used by the main query
    SELECT 
        <fields>
    FROM <table>
    WHERE ...

);

從另一個查詢的結果擷取資料,而不是直接從資料表取用。

$$

  • 將資料處理與分析解耦
  • 查詢更易讀、好理解
  • 提升「可攜性」,更容易調整
  • 可用於 JOINWHERE
Snowflake 中的資料操作

使用子查詢之前

SELECT
    month_num,
    -- windchill - temperature has to be used twice here. What if this changes?
    AVG(windchill - temperature) AS avg_differential
    MIN(windchill - temperature) AS most_differential
FROM weather
WHERE 
    -- Filtering is taking place in the same query as aggregation/analysis
    season = 'Winter' AND
    temperature < 32
GROUP BY month_num;
Snowflake 中的資料操作

使用子查詢之後

-- Start with the subquery, then aggregate

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        |

資料清理後,分析就更容易理解與調整。

Snowflake 中的資料操作

WHERE ... IN ( ... )

...

-- Filter by records with a value in 
-- the subquery result set
WHERE <field> IN (

    SELECT <other-field> FROM ... 

);

建立一個小型結果集,用於轉換、篩選或操作資料。

$$

  • 篩選 IN 非常數的結果集合中的紀錄
  • 也可用在查詢的其他位置
  • 可搭配 AVGMAXMIN
Snowflake 中的資料操作

WHERE ... IN( ... )

SELECT
    todays_date,
    temperature,
    status
FROM weather
WHERE todays_date IN (  -- Filter by all days with home games that were won

    SELECT
        game_date
    FROM game_schedule
    WHERE stadium = 'Home' AND did_win = TRUE

);
Snowflake 中的資料操作

WHERE ... IN ( ... )

使用子查詢找出每場主場比賽天氣資料的查詢結果集

Snowflake 中的資料操作

一起來練習吧!

Snowflake 中的資料操作

Preparing Video For Download...