python - 从python中为postgresql中的union中的每个查询选择特定列

标签 python string postgresql string-formatting psycopg2

我在每个月的时间段内都有相同列的不同表格。我只想从每个表中提取特定的列,然后执行 一个 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/

相关文章:

python - 为 pandas 数据框均匀分配随机值

Python MySQL 日期格式

java - 一个字符串中有多个方法?

java - Scala 代码的 join 函数中的 StringUtils 错误

sql - 为什么我们在数据库列中使用默认值和非空值?

python - 使用 set_yticklabels 会产生水平对齐的刻度标签,而不是垂直对齐

python - 如何同时运行多个 Selenium Firefox 浏览器?

c++ - 不使用库的字符串的字符删除和频率

postgresql - 查询并触发事务内的执行顺序

postgresql - postgresql 服务无法识别 initb -D 和已更改的 data_direectoy