如果一个常数是一个特定的值,省略许多where条件中的一个

2024-05-13 20:06:49 发布

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

我正在从python中从SQL Server提取记录:

REGION = 'HK'
.
.
    where   

                R.rfq_create_date_time >= '""" + START_DATE + """'
                and R.rfq_create_date_time <= '""" + END_DATE + """'
                and R.latest_version = 'Y' 
                and R.sales_book in ('""" + sales_code_string + """')
                and R.Trading_book in ('""" + Trading_Books + """')
                ) as innerTable 
                WHERE rfq_create_time not between '""" + START_TIME + """' and '""" + END_TIME + """'
                order by rfq_create_time"""

    print (strSql)
    print("")
    df_With_NaN = pd.read_sql(strSql, pyodbc.connect(connstr))

如果REGION是HK或SY,我只希望字符串中包含的and R.Trading_book in条件传递给我的连接。在TK的情况下,我希望条件一起被忽略

replace方法是在python中实现这一点的最佳方法还是有替代方法?例如:

REGION = "TK"
strsql = "select * from table where ccy = 'AAA' ######"
if REGION == "HK":
    booklist = "'AAA','BBB','CCC'"
elif REGION == "SY":
    booklist = "'CCC','DDD','FFF'"

if REGION == "TK":
    strsql = strsql.replace("######", "")
else:
    strsql = strsql.replace("######", " and book in (" + booklist + ")")

print (strsql)

Tags: and方法intimecreateregionreplacetk
1条回答
网友
1楼 · 发布于 2024-05-13 20:06:49

另一种可能更具可读性的方法是

if REGION == "HK":
    booklist = "'AAA','BBB','CCC'"
elif REGION == "SY":
    booklist = "'CCC','DDD','FFF'"
else:
    booklist = ""
booklist_clause = "AND book IN ({})".format(booklist) if booklist else ""
strsql = "SELECT * FROM table WHERE ccy = 'AAA' {}".format(booklist_clause)

或者,如果您使用的是python3.6或更高版本,您可以这样做

booklist_clause = f"AND book IN ({booklist})" if booklist else ""
strsql = f"SELECT * FROM table WHERE ccy = 'AAA' {booklist_clause}"

相关问题 更多 >