You cannot use the Aggr function in the script and neither can you use set analysis expressions. You'll have to create tables to collect the values you need to calculate any results and intermediate results. If the variables you use contain expressions then you need to calculate those values first too, probably in more intermediate tables.