为什么需要 CTE 来执行以下操作

Why is a CTE needed to execute the following

以下查询错误,列名无效'rowid'

  SELECT row_number() over (partition by sales_rep order by timestamp desc) as rowid, *
  FROM dbo.you_gettheidea
where rowid = 1

然而,以下版本完美运行。我不知道为什么。

with t1 as (SELECT row_number() over (partition by sales_rep order by timestamp desc) as rowid, *
FROM dbo.you_gettheidea)

Select * from t1
Where rowid = 1

SQL 服务器 12.0.2000

编辑:看来这个问题符合following answered question

您不能在同一语句的 where 子句中使用列别名。它不遵守执行顺序,这就是需要 CTE 的原因。请检查 Execution order

  1. FROM and JOIN s. The FROM clause, and subsequent JOIN s are first executed to determine the total working set of data that is being queried.
  2. WHERE.
  3. GROUP BY.
  4. HAVING.
  5. SELECT.
  6. DISTINCT.
  7. ORDER BY.
  8. LIMIT / OFFSET / TOP

迟到的答案,但还有另一个没有 CTE 或子查询的选项...WITH TIES

Select top 1 with ties *
 From  dbo.you_gettheidea
 Order By row_number() over (partition by sales_rep order by timestamp desc)