SELECT statement not displaying data correctly when using variable and reusing it
The problem is (probably) in the definition of "later".  The query execution is free to evaluate pieces of the query in whatever order it desires.  This makes it difficult to predict whether it is trying to "use" the @ variable before or after it was "set".

And for that reason, @ variables are (or soon will be) deprecated.

If you can provide a small test case with input and desired output, perhaps we can help you rewrite the query to avoid @ variables.