SELECT logcount, logUserID, maxlogtm
, DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
WHERE daysdiff > 120
我得到
无效的列名daysdiff。
Maxlogtm是一个datetime字段。就是这些小事让我抓狂。
SELECT logcount, logUserID, maxlogtm
, DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
WHERE daysdiff > 120
我得到
无效的列名daysdiff。
Maxlogtm是一个datetime字段。就是这些小事让我抓狂。
当前回答
HAVING适用于MySQL 根据文件:
HAVING子句被添加到SQL中,因为WHERE关键字不能 与聚合函数一起使用。
其他回答
在不重复代码的情况下,最有效的方法是使用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
来到这里看起来类似,但有一个CASE WHEN,并像这样使用where结束:where (CASE WHEN COLUMN1=COLUMN2 THEN '1' ELSE '0' END) = 0也许你可以直接在where中使用DATEDIFF。 喜欢的东西:
SELECT logcount, logUserID, maxlogtm
FROM statslogsummary
WHERE (DATEDIFF(day, maxlogtm, GETDATE())) > 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
如果你想在WHERE子句中使用别名,你需要将它包装在一个子选择中,或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