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

2024-09-29 19:33:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有不同的表格,每个月都有相同的列。我只想从每个表中提取特定的列,然后 如下图所示的接头。你知道吗

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

我基本上是想为每个表选择特定的列(基于col\u list)进行UNION。你知道吗


Tags: sampleinfromformatdatacolwhereselect
1条回答
网友
1楼 · 发布于 2024-09-29 19:33:35

通过对占位符编号,您应该能够用相同的值替换多个实例:

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)))

相关问题 更多 >

    热门问题