1

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.

1 Answer 1

2

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)))
Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot @Mureinik. This worked like a charm. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.