It's an old thread, but I'll try to answer specifically the question expressed in the topic.
Why no windowed functions in where clauses?
SELECT
statement has following main clauses specified in keyed-in order:
SELECT DISTINCT TOP list
FROM JOIN ON / APPLY / PIVOT / UNPIVOT
WHERE
GROUP BY WITH CUBE / WITH ROLLUP
HAVING
ORDER BY
OFFSET-FETCH
Logical Query Processing Order, or Binding Order, is conceptual interpretation order, it defines the correctness of the query. This order determines when the objects defined in one step are made available to the clauses in subsequent steps.
----- Relational result
1. FROM
1.1. ON JOIN / APPLY / PIVOT / UNPIVOT
2. WHERE
3. GROUP BY
3.1. WITH CUBE / WITH ROLLUP
4. HAVING
---- After the HAVING step the Underlying Query Result is ready
5. SELECT
5.1. SELECT list
5.2. DISTINCT
----- Relational result
----- Non-relational result (a cursor)
6. ORDER BY
7. TOP / OFFSET-FETCH
----- Non-relational result (a cursor)
For example, if the query processor can bind to (access) the tables or views defined in the FROM
clause, these objects and their columns are made available to all subsequent steps.
Conversely, all clauses preceding the SELECT
clause cannot reference any column aliases or derived columns defined in SELECT
clause. However, those columns can be referenced by subsequent clauses such as the ORDER BY
clause.
OVER
clause determines the partitioning and ordering of a row set before the associated window function is applied. That is, the OVER
clause defines a window or user-specified set of rows within an Underlying Query Result set and window function computes result against that window.
Msg 4108, Level 15, State 1, …
Windowed functions can only appear in the SELECT or ORDER BY clauses.
The reason behind is because the way how Logical Query Processing works in T-SQL
. Since the underlying query result is established only when logical query processing reaches the SELECT
step 5.1. (that is, after processing the FROM
, WHERE
, GROUP BY
and HAVING
steps), window functions are allowed only in the SELECT
and ORDER BY
clauses of the query.
Note to mention, window functions are still part of relational layer even Relational Model doesn't deal with ordered data. The result after the SELECT
step 5.1. with any window function is still relational.
Also, speaking strictly, the reason why window function are not allowed in the WHERE
clause is not because it would create ambiguity, but because the order how Logical Query Processing processes SELECT
statement in T-SQL
.
Links: here, here and here