我在每个月的时间段内都有相同列的不同表格。我只想从每个表中提取特定的列,然后执行 一个 UNION,如下所示。
col_list = ['income', 'urban2', 'marital_stat', 'ethnic_group']
data_sample = str(""" SELECT {} FROM dbo.gold_nov17
where drform in ('NON')
""".format(', '.join(col_list)))
这个对单个表的查询工作得很好。但是,当我尝试进行如下联合时:
data_sample = str(""" SELECT {} FROM dbo.gold_nov17
where drform in ('NON')
-----------
union all
-----------
SELECT {} FROM dbo.gold_nov17
where drform in ('NON')
""".format(', '.join(col_list)))
它抛出错误:
""".format(', '.join(col_list)))
IndexError: tuple index out of range
我基本上想为 UNION 的每个表选择特定的列(基于 col_list)。
最佳答案
通过对占位符进行编号,您应该能够用相同的值替换多个实例:
data_sample = str(""" SELECT {0} FROM dbo.gold_nov17
where drform in ('NON')
-----------
union all
-----------
SELECT {0} FROM dbo.gold_nov17
where drform in ('NON')
""".format(', '.join(col_list)))
关于python - 从python中为postgresql中的union中的每个查询选择特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50810019/