Snowflake 中的数据操作
Jake Roach
Field Data Engineer
子查询是一种工具,可将一个查询的结果供另一个查询使用。
$$
$$
FROM ( ... ) 或 WHERE ... IN ( ... )

SELECT
...
-- 从查询而非表中取数
FROM (
-- 创建将供主查询使用的结果集
SELECT
<fields>
FROM <table>
WHERE ...
);
从另一条查询的结果中取数,而不是直接从表中取。
$$
JOIN、WHERE 等SELECT
month_num,
-- 这里 windchill - temperature 要用两次;若计算变化会怎样?
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 中的数据操作