比较where子句中的两个日期

时间:2015-04-08 03:38:30

标签: sql sql-server tsql

我在Where子句上遇到错误" X"执行此查询时

select top 100 DATEADD(HOUR,10, DateCreated) as X
from y
where X between '2015 -03-31 ' and '2015 -04 -02' 
order by DateCreated desc

2 个答案:

答案 0 :(得分:4)

查询处理阶段的逻辑顺序是:

  1. FROM
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. 选择
  6. ORDER BY
  7. 正如您所见,SELECT之后发生了WHERE。因此,您不能在SELECT子句中使用WHERE部分的任何别名。您只能使用ORDER BY中的别名。

    您的查询应该是这样的:

    SELECT TOP 100 DATEADD(HOUR, 10, DateCreated) AS X
    FROM y
    WHERE DATEADD(HOUR, 10, DateCreated) BETWEEN '2015-03-31' AND '2015-04-02' 
    ORDER BY DateCreated DESC
    

    我还建议您使用

    WHERE DATEADD(HOUR, 10, DateCreated) >= '2015-03-31'
    AND DATEADD(HOUR, 10, DateCreated) <= '2015-04-02'
    

    LOGICAL QUERY PROCESSING

    What do BETWEEN and the devil have in common?

答案 1 :(得分:1)

X是列的别名,因此不能直接在where子句中使用它。

select top 100 DATEADD(HOUR,10, DateCreated) as X
from Table_1
where DATEADD(HOUR,10, DateCreated) between '2015 -03-31 ' and '2015 -04 -02' 
order by DateCreated desc