select 来自 python 的 postgresql 联合中每个查询的特定列
select specific columns for each query in union in postgresql from python
我在每个月的时间段内有不同的 table 相同列。我只想从每个 table 中提取特定的列,然后执行
如下所示的 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)))
这个针对单个 table 的查询工作得很好。但是,当我尝试进行如下联合时:
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
我基本上想要 select 特定列(基于 col_list)为 UNION 的每个 table。
通过给占位符编号,您应该能够用相同的值替换多个实例:
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)))
我在每个月的时间段内有不同的 table 相同列。我只想从每个 table 中提取特定的列,然后执行 如下所示的 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)))
这个针对单个 table 的查询工作得很好。但是,当我尝试进行如下联合时:
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
我基本上想要 select 特定列(基于 col_list)为 UNION 的每个 table。
通过给占位符编号,您应该能够用相同的值替换多个实例:
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)))