SELECT logcount, logUserID, maxlogtm
, DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
WHERE daysdiff > 120
I get
"invalid column name daysdiff".
Maxlogtm is a datetime field. It's the little stuff that drives me crazy.
SELECT logcount, logUserID, maxlogtm
, DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
WHERE daysdiff > 120
I get
"invalid column name daysdiff".
Maxlogtm is a datetime field. It's the little stuff that drives me crazy.
If you don't want to list all your columns in CTE, another way to do this would be to use
outer apply
:If you want to use the alias in your
WHERE
clause, you need to wrap it in a sub select, or CTE:HAVING works in MySQL according to documentation:
How about using a subquery(this worked for me in Mysql)?
The most effective way to do it without repeating your code is use of HAVING instead of WHERE
Normally you can't refer to field aliases in the
WHERE
clause. (Think of it as the entireSELECT
including aliases, is applied after theWHERE
clause.)But, as mentioned in other answers, you can force SQL to treat
SELECT
to be handled before theWHERE
clause. This is usually done with parenthesis to force logical order of operation or with a Common Table Expression (CTE):Parenthesis/Subselect:
Or see Adam's answer for a CTE version of the same.