如何通过单脚本从多SQL国家表提取数据生成多输出并合并结果
修复后的完整实现方案
原代码的核心问题
- SQL语句直接拼接列表
country_name,语法错误,无法识别多个表 - 重复定义完全相同的
summary_tables函数,属于冗余代码 - 未通过循环批量处理国家列表,扩展性差
- 缺少最终导出合并结果的逻辑
优化后的代码实现
import pandas as pd from sqlalchemy import create_engine # 1. 定义需要处理的国家代码列表(注意:加拿大常用代码为CA,需匹配实际表名) country_codes = ["US", "CA"] # 2. 初始化数据库连接(请根据实际环境配置连接参数) engine = create_engine("mssql+pyodbc://your_server/DB?driver=ODBC+Driver+17+for+SQL+Server") # 3. 定义通用的性别统计函数(仅需一个即可复用) def generate_gender_summary(df, country_code): total = df.shape[0] male_count = df[df['sex1'] == 'Male'].shape[0] female_count = df[df['sex1'] == 'Female'].shape[0] # 生成带国家标识的统计结果 summary_df = pd.DataFrame([ ['Male', male_count, round((male_count / total) * 100, 2), country_code], ['Female', female_count, round((female_count / total) * 100, 2), country_code] ], columns=['gender', 'count', 'percentage', 'country']) return summary_df # 4. 批量处理各国数据并收集统计结果 all_summaries = [] for code in country_codes: # 正确拼接单国家表的SQL查询语句 query = f""" SELECT * FROM DB.[Appservices\\DBPowerUsers].[target_{code}_category] """ # 读取当前国家的原始数据 country_df = pd.read_sql(query, engine) # 生成统计结果并加入列表 summary = generate_gender_summary(country_df, code) all_summaries.append(summary) # 5. 合并所有国家的统计结果 merged_summary = pd.concat(all_summaries, ignore_index=True) # 6. 导出结果到CSV(可按需改为Excel等格式) merged_summary.to_csv("gender_statistics_by_country.csv", index=False)
关键优化点说明
- SQL语句拼接:使用f-string格式化语法,循环替换国家代码,确保每个表的查询语句合法
- 通用函数复用:仅保留一个统计函数,通过传入国家代码参数为结果添加标识,消除冗余代码
- 批量处理逻辑:通过循环遍历国家列表,自动处理所有指定国家的数据,新增国家只需在列表中添加代码即可
- 合并方式优化:使用
pd.concat合并多国家统计结果,结构清晰,适配多场景需求 - 导出功能:添加CSV导出逻辑,可根据需求修改为
to_excel等其他导出格式
内容的提问来源于stack exchange,提问作者user19840753
相关产品推荐
相关产品推荐

