As I have seen, your code uses CTE and this strategy can be used for Postgres.
But, can we make a generic strategy, which, is irrespective of whichever database, it can ultimately avoid creating temporary tables.
As, I am facing some permission issue with Oracle and not able to create temporary tables.