Answers:
SELECT
logcount, logUserID, maxlogtm,
DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
WHERE ( 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 innerTable
WHERE daysdiff > 120
或参阅亚当的CTE版本答案。
HAVING
答案不适用于大多数SQL环境,包括此问题所涉及的MS-SQL。(在T-SQL中,HAVING
需要聚合函数。)
如果要在WHERE
子句中使用别名,则需要将其包装在sub 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
无需重复执行代码的最有效方法是使用HAVING而不是WHERE
SELECT logcount, logUserID, maxlogtm
, DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
HAVING daysdiff > 120
HAVING
在别名上使用不是标准的(尽管它确实适用于MySQL)。具体来说,我认为它不适用于SQL Server。
[S0001][207] Invalid column name 'daysdiff'
[S0001][8121] Column 'day' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.
如果您不想在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
您可以引用列别名,但是您需要使用定义它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;
优点:
WHERE/GROUP BY/ORDER BY
sql-server
和t-sql
:)
`daysdiff`
。