This seems to be a major issue with SQL in general:
SELECT
A, B, C,
...
X, Y,
(
SELECT TOP 1
b.R
FROM (
SomeHugeSubqueryThatInclduesAWhereClause
) b
ORDER BY
b.R
) AS Z
FROM (
AlmostTheSameSubqueryThatIncludesAnOnlySlightlyDifferentWhereClause
) a
The problem with using subqueries like this is code duplication. There are a few workarounds to this, including things like temp tables, stored procedures, etc.
At least one issue with those workarounds is that they're relatively involved for something that more general-purpose languages would only need a single line of code for. Other languages allow you to just add a variable real fast and keep referencing it, even if the object that variable's referencing had a deferred-execution iterator or something.
Temp tables might contend a little with the idea of deferred execution. Views, stored procedures, and functions would add more to the DB schema and make it more complicated to deploy and update. All of the above add several lines of boilerplate code and just feel like overengineering for something simple.
So the question is...Is there a good, general-purpose way to avoid code duplication in cases like this, without having something that feels over-engineered and adds several lines on its own?