创建一个动态sql查询,其中从给定的参数生成一个条件

时间:2018-02-09 09:43:18

标签: python dynamic-sql

我有以下SQL查询来获取基于month_id的数据,其中包含年份和月份:

sql_hours = str("""select * from monthly_hours where month_id IN  \
                          (201701,201702,201703,201704,201705,201706,201707,201708,201709,201710,201711,201712) and class = 'Optimal';""")

基表如下:

device_id   month_id    group   hours   tier
53          201705      TX      11.31   Optimal
28          201701      WS      31.56   Sub - Optimal
32          201706      WX      2.93    Optimal
57          201709      TS      2.68    Optimal 
28          201702      OE      0.70    Optimal

此处根据用户想要获取数据和当月的月数,IN()内的值会发生变化。 防爆。当前month_id is 201802以及如果no_of_months = 6,我的查询将变为:

sql_hours = str("""select * from monthly_hours where month_id IN  \
                          (201707,201708,201709,201710,201711,201712) and class = 'Optimal';""")

数据滞后2个月,因此最新数据将是2017年12月(2月当前月份),而3月最新数据为201801。所以month_id's have to fall within 201707 and 201712。 如果no_of_months = 12,那么month_id必须fall within 201701 and 201712.

有人可以帮我这个吗?我不确定在python !!中可以进行多少sql查询参数化。

1 个答案:

答案 0 :(得分:0)

你可以用变量更新查询字符串,使用dates = '201707,201708,201709,201710,201711,201712' sql_hours = str("select * from monthly_hours where month_id IN \ ({}) and class = 'Optimal';".format(dates)) 进行参数化,例如:

{{1}}