ROW_NUMBER错误

时间:2012-07-18 08:51:17

标签: sql sql-server-2008

SELECT [Column1] FROM VIEW1 WHERE ROW_NUMBER = 5;

给出错误:

  

消息207,级别16,状态1,行2无效的列名称'ROW_NUMBER'。

为什么有任何建议? ROW_NUMBER自动以粉红色着色,这意味着从我的知识“关键字” - 所以为什么Sql Server认为它应该是一列并且说该列不存在?

提前谢谢。

4 个答案:

答案 0 :(得分:5)

您不能在此上下文中使用ROW_NUMBER。可以在此处看到在WHERE子句中使用ROW_NUMBER的示例:

USE AdventureWorks2012;
GO
WITH OrderedOrders AS
(
    SELECT SalesOrderID, OrderDate,
    ROW_NUMBER() OVER (ORDER BY OrderDate) AS RowNumber
    FROM Sales.SalesOrderHeader 
) 
SELECT SalesOrderID, OrderDate, RowNumber  
FROM OrderedOrders 
WHERE RowNumber BETWEEN 50 AND 60;

来源:http://msdn.microsoft.com/en-us/library/ms186734.aspx

答案 1 :(得分:5)

处理查询的方式是错误的,因为

ROW_NUMBER返回序列号  结果集的分区中的一行,  从1开始,每个分区的第一行。

你可以尝试

Select 
from 
(
        Select row_number() over (partition by x order by x)SrNo,* from x
)A
where A.SrNo=1

答案 2 :(得分:1)

你不能像那样使用ROW_NUMBER()

SELECT * FROM 
(
    SELECT [Column1], ROW_NUMBER() OVER(ORDER By [Column1] ASC) As Row
    FROM VIEW1
) x
WHERE Row = 5;

答案 3 :(得分:0)

您必须先定义ROW_NUMBER。试试这个......

SELECT [column1] FROM (
  SELECT
    ROW_NUMBER() OVER (ORDER BY key ASC) AS rownumber,
    [column1]
  FROM <tablename>
) AS xyz
WHERE rownumber = 5

例如:

SELECT EmpName FROM (
  SELECT
    ROW_NUMBER() OVER (ORDER BY empId ASC) AS rownumber,
    EmpName
  FROM EmpMaster
) AS EmpTable
WHERE rownumber = 5

您可以使用查看代替