At issue is that the scripting language is deceptively similar to the UI expressions language - but not the same! The two differences that are tripping you up are
1. set expressions are not supported in scripts
2. aggregation functions are only for evaluation in the context of LOAD or SELECT statements.
So, if you really want to get an aggregated value into a variable, you'd need to construct a LOAD statement that calculates the aggregation you want and has a WHERE clause to do the filtering that's equivalent to your set expression, and that results in a single record containing that value
and then use peek() to get the value into your variable.