0
我在PYTHON的SQL查詢中多次使用CASE語句時遇到問題。 我想知道是否可以拿走CASE語句並創建一個模板,然後我可以將模板參數放回到原始查詢中。就像這樣:Python,將case語句插入sql查詢
case_stm_template =
crs.execute("""
CASE
WHEN level_1 = 'Corporate'
THEN
CASE
WHEN ssr.rating = 'A' OR ssr.rating LIKE 'A[+-]'
THEN 'Corp A'
WHEN ssr.rating = 'AA' OR ssr.rating LIKE 'AA[+-]'
THEN 'Corp AA'
WHEN ssr.rating = 'BBB' OR ssr.rating LIKE 'BBB[+-]'
THEN 'Corp BBB'
ELSE NULL
END
WHEN level_1 = 'Government' AND level_2 = 'Provincial'
THEN 'Prov'
WHEN level_1 = 'Government' AND level_2 = 'Federal'
THEN 'Canada'
ELSE NULL
END
""")
要把它放到
crs.execute("""
SELECT
...
case_stm_template,
SUM(...)
FROM ....
WHERE ....
GROUP BY
case_stm_template
""".format(...))
這是行不通的。誰能幫我?謝謝!!!