是否可以在 SQL Server 中的 where 或having 子句中使用自定义字段?

Zip*_*per 2 sql sql-server sql-server-2008-r2

我正在尝试以下 SQL 查询:

  select (execution_end_timestamp - execution_queued_timestamp) as totalTime, execution_queued_timestamp from exec_queue
  where execution_name like '%Generate%'
  and execution_queued_timestamp > '2012-10-04 20:00:00.000'
  having totalTime < '1900-01-01 00:00:06.000'
Run Code Online (Sandbox Code Playgroud)

我尝试在 where 和having 子句中使用totalTime,但在这两种情况下都不起作用。我还尝试了 datediff 希望这可能有效,但结果相同。

有没有可以在 where 或having 子句中使用计算字段的技巧?除了使用聚合函数的情况外,谷歌搜索没有发现任何结果。

Joh*_*Woo 5

不,子句中不允许使用别名WHERE,请尝试,

select (execution_end_timestamp - execution_queued_timestamp) as totalTime, execution_queued_timestamp 
from exec_queue
where execution_name like '%Generate%' AND
      execution_queued_timestamp > '2012-10-04 20:00:00.000' AND
      (execution_end_timestamp - execution_queued_timestamp) < '1900-01-01 00:00:06.000'
Run Code Online (Sandbox Code Playgroud)

为什么对and子句ALIAS不起作用的原因,WHEREHAVING

  • 首先形成所有表的乘积from clause。
  • 然后where clause评估 来消除不满足 search_condition 的行。
  • 接下来,使用 中的列对行进行分组group by clause。
  • 然后,e中不满足search_condition的Grouphaving claus被淘汰。
  • select clause接下来,计算目标列表中的表达式。
  • 如果distinct keywordselect 子句中存在 in ,则现在会消除重复行。
  • 是union在评估每个子选择之后获取的。
  • 最后,结果行根据 中指定的列进行排序order by clause。