Referring to a Column Alias in a WHERE Clause

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

I get

9条回答
  •  -上瘾入骨i
    2020-11-22 05:57

    You could refer to column alias but you need to define it using CROSS/OUTER APPLY:

    SELECT s.logcount, s.logUserID, s.maxlogtm, c.daysdiff
    FROM statslogsummary s
    CROSS APPLY (SELECT DATEDIFF(day, s.maxlogtm, GETDATE()) AS daysdiff) c
    WHERE c.daysdiff > 120;
    

    DBFiddle Demo

    Pros:

    • single definition of expression(easier to maintain/no need of copying-paste)
    • no need for wrapping entire query with CTE/outerquery
    • possibility to refer in WHERE/GROUP BY/ORDER BY
    • possible better performance(single execution)

提交回复
热议问题