如何在Snowflake中提取两列去重值并生成新表单列
在Snowflake中合并两列去重值为单列的解决方案
输入示例表(table1)
| Vegetables | Fruits |
|---|---|
| Carrot | Apple |
| Potato | Banana |
| Carrot | Apple |
| Tomato | Orange |
| Potato | Banana |
预期输出表
| Combined_Items |
|---|
| Carrot |
| Potato |
| Tomato |
| Apple |
| Banana |
| Orange |
实现SQL代码
方案1:创建持久化新表
CREATE OR REPLACE TABLE combined_items_table AS SELECT Vegetables AS combined_items FROM table1 UNION SELECT Fruits AS combined_items FROM table1;
方案2:仅查询结果(不建表)
SELECT combined_items FROM ( SELECT Vegetables AS combined_items FROM table1 UNION SELECT Fruits AS combined_items FROM table1 );
关键说明
- 用
UNION而非UNION ALL:UNION会自动对合并后的数据集去重,正好匹配需求;如果用UNION ALL会保留所有重复值,之后还要额外加DISTINCT,反而多此一举。 CREATE OR REPLACE TABLE:会直接创建新表,若已有同名表则覆盖。如果不想覆盖原有表,改成CREATE TABLE IF NOT EXISTS即可。
内容的提问来源于stack exchange,提问作者Void S
相关产品推荐
相关产品推荐

