1

I'm trying the following SQL query:

  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'

I've tried using the totalTime in the where and having clause and in both cases it doesn't work. I also tried datediff hoping that might work, but it had identical results.

Is there a trick where you can use a computed field in a where or having clause? Googling around hasn't turned up anything except in cases where an aggregating function is used.

4

2 回答 2

4

不,子句中不允许使用别名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'

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

  • 首先形成中所有表的乘积from clause
  • 然后where clause评估 以消除不满足 search_condition 的行。
  • 接下来,使用 中的列对行进行分组group by clause
  • having claus然后,排除 e 中不满足 search_condition 的组。
  • 接下来,select clause评估目标列表中的表达式。
  • 如果distinct keywordselect 子句中存在 in,则现在消除重复行。
  • union评估每个子选择之后进行。
  • 最后,结果行根据order by clause.
于 2012-10-05T02:01:44.460 回答
3

我曾经有指向 SQL-92、99 和 2003 ISO 标准的链接,但现在可以使用此链接

基本上,查询执行的顺序是

1. FROM/JOIN
2. WHERE/ON   -- exception for LEFT JOIN
3. GROUP BY (incl. CUBE, ROLLUP, GROUPING SETS)
4. HAVING
5. SELECT
6. DISTINCT
7. ORDER BY

因此,您为 SELECT 列创建的别名对 WHERE 和 HAVING 阶段不可见。它实际上只是表达式的复制和粘贴,非常琐碎。边缘情况可能是当您处理长而复杂的公式时,子查询可能会更好,例如

select totalTime,
       execution_queued_timestamp
from (
    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'
) x
where totalTime < '1900-01-01 00:00:06.000'

我给你一个提示。SQL Server 实际上知道将 WHERE 过滤器带入内部查询并将其应用于基表,因此不会损失性能!

于 2012-10-05T02:08:19.140 回答