Just a guess, but could this be it?
In the line:
select type, sub_type, amount from (select rank() over(order by count(distinct(ftr_id)) desc) r,');
Type is a keyword. You should qualify type column with the table or surround it with quotes ("TYPE")
See the explanation here.[
^]
It compiles because sqlquery is correct string, but when called to open a cursor it fails. You should output your sqlquery to console and then check it separately. This is good practice for all dynamic sql queries.
If this helps, please take time to accept the solution. Thank you.