Referring to a Column Alias in a WHERE Clause

后端 未结 9 2122
你的背包
你的背包 2020-11-22 05:38
SELECT logcount, logUserID, maxlogtm
   , DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
WHERE daysdiff > 120

I get

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 05:53

    SELECT
       logcount, logUserID, maxlogtm,
       DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
    FROM statslogsummary
    WHERE ( DATEDIFF(day, maxlogtm, GETDATE() > 120)
    

    Normally you can't refer to field aliases in the WHERE clause. (Think of it as the entire SELECT including aliases, is applied after the WHERE clause.)

    But, as mentioned in other answers, you can force SQL to treat SELECT to be handled before the WHERE clause. This is usually done with parenthesis to force logical order of operation or with a Common Table Expression (CTE):

    Parenthesis/Subselect:

    SELECT
       *
    FROM
    (
       SELECT
          logcount, logUserID, maxlogtm,
          DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
       FROM statslogsummary   
    ) as innerTable
    WHERE daysdiff > 120
    

    Or see Adam's answer for a CTE version of the same.

提交回复
热议问题