-
冉冉说
SELECT
logcount, logUserID, maxlogtm,
DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiffFROM statslogsummaryWHERE ( DATEDIFF(day, maxlogtm, GETDATE() > 120)通常,您不能引用WHERE条款。(把它想象成整个SELECT包括别名,则在WHERE条款)但是,正如其他答案中提到的,您可以强制sql处理SELECT将在WHERE条款。这通常使用括号强制执行逻辑操作顺序,或者使用公共表达式(CTE):括号/子选择:SELECT
*FROM(
SELECT
logcount, logUserID, maxlogtm,
DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff FROM statslogsummary
) as innerTableWHERE daysdiff > 120或者看亚当的答案,一个相同的CTE版本。
-
MMMHUHU
如果要在WHERE子句中,您需要将其包装在子SELECT中,或CTE:WITH LogDateDiff AS( SELECT logcount, logUserID, maxlogtm , DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff FROM statslogsummary)SELECT logCount, logUserId, maxlogtm, daysdiffFROM LogDateDiffWHERE daysdiff > 120
-
绝地无双
如果不想列出CTE中的所有列,另一种方法是使用outer apply:select
s.logcount, s.logUserID, s.maxlogtm,
a.daysdifffrom statslogsummary as s outer apply (select datediff(day, s.maxlogtm, getdate()) as daysdiff) as awhere a.daysdiff > 120