我在每月时段有不同的相同列表。我想从每个表中只拉出特定列,然后执行 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)。
答案 0 :(得分:2)
通过对占位符进行编号,您应该能够使用相同的值替换多个实例:
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)))