如何用Snowpark Python执行SQL Minus操作并定位差异列?
需求背景
现有两张数据表:
Table 1
| I'd | Name | Balance |
|---|---|---|
| 1 | AB | 100 |
| 2 | BC | 200 |
Table 2
| I'd | Name | Balance |
|---|---|---|
| 1 | AB | 110 |
| 2 | CD | 200 |
原SQL MINUS操作
Select "I'd", Name, Balance from table1 Minus Select "I'd", Name, Balance from table2
原MINUS执行结果
| I'd | Name | Balance |
|---|---|---|
| 1 | AB | 100 |
需求:在Snowflake Python工作表中实现上述逻辑,仅存储两表中存在差异的列名及对应值。
Snowflake Python实现方案
核心逻辑:先筛选出Table1独有的行(模拟MINUS),再针对这些行对比两表列值,只保留差异列的信息。
代码实现
import snowflake.connector import pandas as pd from snowflake.connector.pandas_tools import write_pandas # 1. 建立Snowflake连接 conn = snowflake.connector.connect( user='你的用户名', password='你的密码', account='你的账户标识', warehouse='你的仓库名', database='你的数据库名', schema='你的模式名' ) # 2. 读取两表数据为DataFrame def load_table_data(table_name): query = f'SELECT "I\'d", NAME, BALANCE FROM {table_name}' return pd.read_sql(query, conn) df_table1 = load_table_data('TABLE1') df_table2 = load_table_data('TABLE2') # 3. 模拟SQL MINUS:提取Table1中不在Table2的行 table1_rows = set(df_table1.itertuples(index=False, name=None)) table2_rows = set(df_table2.itertuples(index=False, name=None)) unique_table1_rows = [row for row in table1_rows if row not in table2_rows] # 4. 提取差异列信息(假设I'd为唯一主键) diff_records = [] for row in unique_table1_rows: # 定位Table1中当前行的完整数据 table1_row = df_table1[(df_table1["I'd"] == row[0]) & (df_table1["NAME"] == row[1]) & (df_table1["BALANCE"] == row[2])].iloc[0] # 定位Table2中同主键的行 table2_row = df_table2[df_table2["I'd"] == row[0]] if not table2_row.empty: table2_row = table2_row.iloc[0] diff_details = {"I'd": row[0]} # 逐列对比取值,记录差异 for col in df_table1.columns: if table1_row[col] != table2_row[col]: diff_details[f"{col}_TABLE1"] = table1_row[col] diff_details[f"{col}_TABLE2"] = table2_row[col] diff_records.append(diff_details) # 5. 将差异结果写入Snowflake表 diff_df = pd.DataFrame(diff_records) write_pandas(conn, diff_df, 'TABLE_DIFFERENCES') # 关闭连接 conn.close()
最终存储结果
执行后,TABLE_DIFFERENCES表会存储如下内容,仅保留差异列信息:
| I'd | BALANCE_TABLE1 | BALANCE_TABLE2 |
|---|---|---|
| 1 | 100 | 110 |
内容的提问来源于stack exchange,提问作者sushanto sarkar
相关产品推荐
相关产品推荐

