Referring to a Column Alias in a WHERE Clause

后端 未结 9 2029
你的背包
你的背包 2020-11-22 05:38
SELECT logcount, logUserID, maxlogtm
   , DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
WHERE daysdiff > 120

I get

相关标签:
9条回答
  • 2020-11-22 06:18

    The most effective way to do it without repeating your code is use of HAVING instead of WHERE

    SELECT logcount, logUserID, maxlogtm
       , DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
    FROM statslogsummary
    HAVING daysdiff > 120
    
    0 讨论(0)
  • 2020-11-22 06:18

    If you don't want to list all your columns in CTE, another way to do this would be to use 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
    
    0 讨论(0)
  • 2020-11-22 06:18

    Came here looking something similar to that, but with a CASE WHEN, and ended using the where like this: WHERE (CASE WHEN COLUMN1=COLUMN2 THEN '1' ELSE '0' END) = 0 maybe you could use DATEDIFF in the WHERE directly. Something like:

    SELECT logcount, logUserID, maxlogtm
    FROM statslogsummary
    WHERE (DATEDIFF(day, maxlogtm, GETDATE())) > 120
    
    0 讨论(0)
提交回复
热议问题