如何使用 Python 迭代创建 UNION ALL SQL 语句?
How to iteratively create UNION ALL SQL statement using Python?
我正在连接到 Snowflake
以查询来自 Snowflake
的视图 table 的行计数数据。我也在查询与 View table 相关的元数据。我的查询如下所示。我想知道我是否可以使用 python
遍历 UNION ALL 语句?当我尝试 运行 我的以下查询时,我收到一条错误消息,提示“view_table_3”不存在。
提前感谢您的时间和努力!
查询获取 Snowflake 视图的行数 table(带元数据)
view_tables=['view_table1','view_table2','view_table3','view_table4']
print(f""" SELECT * FROM (SELECT TABLE_SCHEMA,TABLE_NAME,CREATED,LAST_ALTERED FROM SCHEMA='INFORMATION_SCHEMA.VIEWS' WHERE TABLE_SCHEMA='MY_SCHEMA' AND TABLE_NAME IN ({','.join("'" +x+ "'" for x in view_tables)})) t1
LEFT JOIN
(SELECT 'view_table1' table_name2, count(*) as view_row_count from MY_DB.SCHEMA.view_table1
UNION ALL SELECT {','.join("'" +x+ "'" for x in view_tables[1:])},count(*) as view_row_count from MY_DB.SCHEMA.{','.join("" +x+ "" for x.replace("'"," ") in view_tables)})t2
on t1.TABLE_NAME =t2.table_name2 """)
如果要动态联合,请将整个 SELECT
查询放入生成器中,然后用 ' UNION '
加入它们。
sql = f'''SELECT * FROM INFORMATION_SCHEMA.VIEWS AS v
LEFT JOIN (
{' UNION '.join(f"SELECT '{table}' AS table_name2, COUNT(*) AS view_row_count FROM MY_SCHEMA.{table}" for table in view_tables)}
) AS t2 ON v.TABLE_NAME = t2.table_name2
WHERE v.TABLE_NAME IN ({','.join(f"'{table}'" for table in view_tables)})
'''
print(sql);
我正在连接到 Snowflake
以查询来自 Snowflake
的视图 table 的行计数数据。我也在查询与 View table 相关的元数据。我的查询如下所示。我想知道我是否可以使用 python
遍历 UNION ALL 语句?当我尝试 运行 我的以下查询时,我收到一条错误消息,提示“view_table_3”不存在。
提前感谢您的时间和努力!
查询获取 Snowflake 视图的行数 table(带元数据)
view_tables=['view_table1','view_table2','view_table3','view_table4']
print(f""" SELECT * FROM (SELECT TABLE_SCHEMA,TABLE_NAME,CREATED,LAST_ALTERED FROM SCHEMA='INFORMATION_SCHEMA.VIEWS' WHERE TABLE_SCHEMA='MY_SCHEMA' AND TABLE_NAME IN ({','.join("'" +x+ "'" for x in view_tables)})) t1
LEFT JOIN
(SELECT 'view_table1' table_name2, count(*) as view_row_count from MY_DB.SCHEMA.view_table1
UNION ALL SELECT {','.join("'" +x+ "'" for x in view_tables[1:])},count(*) as view_row_count from MY_DB.SCHEMA.{','.join("" +x+ "" for x.replace("'"," ") in view_tables)})t2
on t1.TABLE_NAME =t2.table_name2 """)
如果要动态联合,请将整个 SELECT
查询放入生成器中,然后用 ' UNION '
加入它们。
sql = f'''SELECT * FROM INFORMATION_SCHEMA.VIEWS AS v
LEFT JOIN (
{' UNION '.join(f"SELECT '{table}' AS table_name2, COUNT(*) AS view_row_count FROM MY_SCHEMA.{table}" for table in view_tables)}
) AS t2 ON v.TABLE_NAME = t2.table_name2
WHERE v.TABLE_NAME IN ({','.join(f"'{table}'" for table in view_tables)})
'''
print(sql);