Create a summary table where you calculate all the aggregations like linest_m and linest_b grouped by the three dimensions of your straight table. All the fields need to be in the same table. So you need to join the two tables first.
You can't use set analysis in the script so you'll have to use where clauses instead to select only the records you need. And you're using variables which may or may not have any value in the script. Make sure that they do.