是否存在查询As函数数据的语法?

时间:2013-05-21 13:36:39

标签: sql

使用函数后,是否可以在SQL中查询字段名称?

所以例如

select datediff(hh, startdate, enddate) as HoursBetween
from tbl
where HoursBetween > 0

3 个答案:

答案 0 :(得分:4)

不幸的是,您不能使用与ALIAS子句在同一级别创建的WHERE,因为WHERE子句正在SELECT子句之前执行。你有两个选择,

一,直接在WHERE子句中使用表达式。

select datediff(hh, startdate, enddate) as HoursBetween 
from tbl 
where datediff(hh, startdate, enddate) > 0

二,将语句包装在子查询中。

SELECT *
FROM
(
    select datediff(hh, startdate, enddate) as HoursBetween 
    from tbl 
) ss
WHERE ss.HoursBetween > 0

这是SQL Order of Operation

  • FROM clause
  • WHERE子句
  • GROUP BY子句
  • HAVING条款
  • SELECT条款
  • ORDER BY子句

答案 1 :(得分:2)

SELECT * 
FROM (select datediff(hh, startdate, enddate) as HoursBetween
from tbl) AS I
WHERE HoursBetween > 0

答案 2 :(得分:1)

在MySQL上可以使用 HAVING 子句:

SELECT datediff(hh, startdate, enddate) AS HoursBetween FROM tbl
HAVING HoursBetween > 0