Instruction
Great, now we can get down to work. Back in Part 1, we said that you can't use window functions in the WHERE clause. Why is that so? Because all query elements are processed in a very strict order:
FROM– SQL Server gets data from tables in theFROMclause and, if necessary, performs theJOINs (INNER,LEFT,RIGHTandFULL)WHERE– The data is filtered by the conditions specified in theWHEREclauseGROUP BY– The data is grouped by the conditions specified in theWHEREclause,- Aggregate Functions are applied to the groups created in the
GROUP BYphase HAVING– The aggregated groups are filtered by the condition given in theHAVINGclause- Window Functions
SELECT– SQL Server selects the given columnsDISTINCT– Repeated values are removedUNION/INTERSECT/EXCEPT– SQL Server applies set operationsORDER BY– the results are sortedOFFSET– One or more rows are skippedFETCH/TOP– only the first rows are selected
Practically, this order means that you can't put window functions anywhere in the FROM, WHERE, GROUP BY or HAVING clauses. This is because at the time of calculating these elements, window functions are not yet calculated – and it's impossible to use something which is not already available.
Exercise
Find out for yourself that window functions don't work in the WHERE clause. Look at the template: we would like to show some information for those auctions which have a higher FinalPrice than the average FinalPrice.
Try to run this query.
When you're done, click to continue.



