繁体   English   中英

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

[英]Is it possible to use a custom field in where or having clause in SQL Server?

我正在尝试以下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'

我试过在where和have子句中使用totalTime,在两种情况下均不起作用。 我也尝试过datediff希望能奏效,但结果相同。

有没有技巧可以在where或haveing子句中使用计算字段? 除了使用聚合功能的情况外,谷歌搜索没有任何作用。

否, 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'

ALIAS无法在WHEREHAVING子句上运行的原因,

  • 首先,形成from clause中所有表的乘积。
  • 然后对where clause求值以消除不满足search_condition的行。
  • 接下来,使用group by clause的列对行进行分组。
  • 然后,消除having claus e中不满足search_condition的组。
  • 接下来,对select clause目标列表中的表达式进行求值。
  • 如果select子句中存在distinct keyword ,则现在消除重复的行。
  • union是各个子选择进行评估后作出。
  • 最后,结果行将根据order by clause指定的列进行排序。

我曾经有到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筛选器带入内部查询并将其应用于基表,因此不会损失性能!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM