【问题标题】:Omit one of the many where conditions if a constant is a specific value如果常量是特定值,则省略许多 where 条件之一
【发布时间】:2019-03-17 09:59:45
【问题描述】:

我正在从 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 的情况下,我希望将条件全部忽略。

替换方法是在 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)

【问题讨论】:

标签: python sql pandas replace pyodbc


【解决方案1】:

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

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)

或者,如果您使用的是 Python 3.6 或更高版本,您可以这样做

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

【讨论】:

  • 感谢@Gord Thompson,我不知道 python 中的 F 字符串。这个很有用!!
猜你喜欢
  • 2018-12-23
  • 2013-08-18
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
  • 2014-03-08
相关资源
最近更新 更多