Skip to content
Advertisement

Python – Running a SQL in a loop based on column value

I am trying to build a SQL query that runs based on certain conditions (if a column is filled run Query 1 else Query 2 and so on) as shown below:

I am trying to build something like the above but the number of fields as variable (fields like col_a and col_b) are 6 in number. Is there a way I can perform this in a loop based on the length of field, instead of having to manually have each condition explicitly mentioned as I have done above.

Advertisement

Answer

You should keep values on list or in dictionary and then you can use for-loop to filter empty elements.

Later you can use string functions and for-loop to convert to col = val and join() to connect these elements using word AND, etc.

Results:

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement