引用WHERE子句中的列别名

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

我得到“无效的列名daysdiff”。 Maxlogtm是一个date时间字段。 这是让我疯狂的小东西。

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

通常你不能在WHERE子句中引用字段别名。 (把它看作包含别名的整个SELECT ,是在WHERE子句之后应用的。)

但是,正如其他答案中所提到的,您可以强制SQL将SELECT视为在WHERE子句之前处理。 这通常使用圆括号来强制执行操作的逻辑顺序或使用公用表expression式(CTE):

括号/子select:

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

或者看到亚当的CTE版本的答案是一样的。

如果要在WHERE子句中使用别名,则需要将其包装在子select或CTE中 :

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

如果你不想在CTE中列出所有的列,另一种方法是使用outer apply

 select s.logcount, s.logUserID, s.maxlogtm, a.daysdiff from statslogsummary as s outer apply (select datediff(day, s.maxlogtm, getdate()) as daysdiff) as a where a.daysdiff > 120 

在不重复你的代码的情况下,最有效的方法是使用HAVING而不是WHERE

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

如何使用子查询(这在Mysql中为我工作)?

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

HAVING根据文档在MySQL中工作:

HAVING子句已添加到SQL,因为WHERE关键字不能用于聚合函数。