My problem statement is bit unique.
I am trying to generate a sql
string recursively that would contain UNION and JOIN using python.
Below are the conditions:
-
Number of columns would be determined from a variable. If v = 2 the number of columns would be 3, with 1st one would always be fixed. If v = 3 the number of columns would be 4 with 1st one would always be fixed.
-
In each UNION block the number of join : number of columns – 1. And this would be increasing in numbers in each UNION block till the time the loop reaches v-1.
-
Number of UNION : v-1
-
Number of columns that would take
NULL
value (i.e.null as
) in each UNION block : v-1. And this would keep on decreasing like v-2,v-3 in each subsequent UNION block till it reaches 0
With the above two conditions let me show the desired output.
v = 2
tables = ['t1','t2'] #<---number of tables would be fixed
select
a.col_1 #<---This would be fixed
,a0.col_2
,null as col_3
from t1 a
left join t2 a0
on a.col_1 = a0.col_1 and a0.level = 1
union all
select
a.col_1
,a0.col_2
,a1.col_3 #<----the null is being replaced by actual column col_3
from table1 a
left join t2 a0
on a.col_1=a0.col_1 and a0.level = 1
left join t2 a1 #<----please observe that same table t1 is being aliased differently
on a.col_1 = a1.col_1 and a1.level = 2
Now what I have worked:
v=2
sql_b = 'select a.col_1'
tables = ['t1','t2']
join ='LEFT Join t2'
col = ''
for i in range(v):
col = col + 'NULL AS col_{0}'.format(i+1)
sql+=col + ' ' + 'FROM final_h c ' + join_s + ' a{0}'.format(i)+
' ON c.col_+1 = a{}.col_1 AND a{}.level = 1 '.format(i,i)
print(sql)
But this approach is not working.
-
Comma is not coming properly
-
Not able to include
UNION
part
Any help would be appreciated.