Shuvayan Das
Shuvayan Das

Reputation: 1048

select specific columns for each query in union in postgresql from python

I have different tables of same columns across monthly time periods. I want to pull only specific columns from each table and then do a UNION as shown below.

col_list = ['income', 'urban2', 'marital_stat', 'ethnic_group']

data_sample = str(""" SELECT {} FROM dbo.gold_nov17 
                            where drform in ('NON')
                            """.format(', '.join(col_list)))

This query on a single table works just fine. However when I try to do a union as below:

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

It throws error:

""".format(', '.join(col_list)))

IndexError: tuple index out of range

I am essentially wanting to select specific columns(based on col_list) for each of the tables for UNION.

Upvotes: 1

Views: 228

Answers (1)

Mureinik
Mureinik

Reputation: 311798

By numbering your placeholders you should be able to replace multiple instance with the same value:

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

Upvotes: 2

Related Questions