I have the below SQL query to fetch data based on month_id which contains the year and month:
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';""")
the base table looks like:
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
Here based on the number of months user wants to take data of and current month the values inside IN() would change.
Ex. Current month_id is 201802
and if no_of_months = 6
, my query would become:
sql_hours = str("""select * from monthly_hours where month_id IN \
(201707,201708,201709,201710,201711,201712) and class = 'Optimal';""")
There is a lag of 2 months for data and hence the latest data would be of 201712(for current month of Feb.However in March the latest data would be of 201801). so the month_id's have to fall within 201707 and 201712
.
If the no_of_months = 12
then the month_id's have to fall within 201701 and 201712.
Can someone please help me with this? I am not sure how so much parameterization of the sql query can be done in python!!