Search code examples
sqlsql-servert-sqllaghaving

Can LAG be used with HAVING?


I distinctly recall that T-SQL will never let you mix LAG and WHERE. For example,

SELECT FOO
WHERE LAG(BAR) OVER (ORDER BY DATE) > 7

will never work. T-SQL will not run it no matter what you do. But does T-SQL ever let you mix LAG with HAVING?

Note: All that an answer needs to do is either give a theory-based or documentation-based reason why it does not, or give any example at all of where it does.


Solution

  • From Logical Processing Order of the SELECT statement:

    The following steps show the logical processing order, or binding order, for a SELECT statement......

    1. FROM
    2. ON
    3. JOIN
    4. WHERE
    5. GROUP BY
    6. WITH CUBE or WITH ROLLUP
    7. HAVING
    8. SELECT
    9. DISTINCT
    10. ORDER BY
    11. TOP

    Window functions are evaluated at the level of SELECT, which comes after HAVING, so the answer is no you can't use window functions in the HAVING clause.