Row_Number在where where子句中不可用

时间:2015-01-30 10:38:05

标签: sql-server row-number

我正在尝试使用Row_Number,它在order by子句中工作正常,但是当在where子句中使用它时,我得到无效的列,那dosnt对我有意义吗?

有谁可以解释为什么会这样?非常感谢

SELECT col1,col2,
ROW_NUMBER() OVER(PARTITION BY col2 ORDER BY col2) as rownr
FROM  table1 t1 WITH(NOLOCK) 
JOIN table2 t2 WITH(NOLOCK) ON t2.id = t1.id
WHERE rownr > 1
ORDER BY rownr,unit

2 个答案:

答案 0 :(得分:3)

processing的逻辑order by位于select之后,where子句在select之前处理,这就是您收到错误的原因。

为此,您应该将查询设为sub-select并过滤外部查询中的记录

SELECT col1,
       col2
FROM  (SELECT col1,
              col2,
              Row_number()OVER(PARTITION BY col2 ORDER BY col2) AS rownr,
              unit
       FROM   table1 t1 WITH(NOLOCK)
              JOIN table2 t2 WITH(NOLOCK)
                ON t2.id = t1.id) a
WHERE  rownr > 1
ORDER  BY rownr, unit 

点击此处查看有关Logical Processing Order of the SELECT statement

的更多信息

答案 1 :(得分:2)

ROW_NUMBER()不能与同一查询一起使用。在外部查询中设置ORDER BY

编辑:由于您在一个地方计算ROW_NUMBER(),因此无法在同一查询中使用rownr。您可以在外部查询中访问rownr

SELECT * FROM
(
   SELECT col1,col2,unit,
   ROW_NUMBER() OVER(PARTITION BY col2 ORDER BY col2) as rownr
   FROM  table1 t1 WITH(NOLOCK) 
   JOIN table2 t2 WITH(NOLOCK) ON t2.id = t1.id       
)TAB
WHERE rownr > 1
ORDER BY rownr,unit