简体   繁体   中英

How to use a case statement in python

I have a part of the code which checks for zero and gives pass or fail

l=[dbname,tbname,python,fact, game_table]
f_query  = "select case when count(*)=1 then 'Pass' else 'Fail' end result"
f_query += " from  qa."+row.DB_NAME
f_query += " where "+ row.Field_NAME + "=0"

How can I include another when statement within this code where I need to get from a list or tuple which has l=[dbname,tbname,python,fact, game_table] which are in row.DB_NAME but when they are present then the result should be 'exp'. So, I tried something like this:

l=[dbname,tbname,python,fact, game_table]
f_query  = "select case when count(*)=1 then 'Pass' when row.DB_Name in l then 'exp'
            else 'Fail' end result"
f_query += " from  qa."+row.DB_NAME
f_query += " where "+ row.Field_NAME + "=0"

But this din't work. Can someone help me with this

You can join the list into a string and use a table alias to stitch together your SQL:

l=[dbname,tbname,python,fact, game_table]
f_query  = "select case when count(*)=1 then 'Pass'"
f_query += " when t1 in ({}) then 'exp'".format(','.join(l))
f_query += " else 'Fail' end result"
f_query += " from qa."+row.DB_NAME+" as t1"
f_query += " where "+ row.Field_NAME + "=0"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM