ROW_NUMBER()Sql错误

时间:2015-06-11 12:45:40

标签: sql-server-2008

我正在处理我的项目,我必须创建一个SQL查询来实现我的目标。但不幸的是,当我运行查询时,我收到一个错误。

这是我的Sql查询:

select ROW_NUMBER() 
OVER (ORDER BY Advertisement.AdsDate asc ) AS AdsIndex 
,Advertisement.AdsId , Advertisement.AdsEnTitle from Advertisement
where Advertisement.Status=N'True' and AdsIndex<=17 and AdsIndex>=11

错误:

  

无效的列名称'AdsIndex'。

我该如何解决我的问题?

3 个答案:

答案 0 :(得分:1)

您不能在where子句中引用ROW_NUMBER。见这篇相关文章:

SQL Row_Number() function in Where Clause

尝试将上面的查询包装在CTE或子查询中并从那里过滤。

编辑:更多背景:

Row_Number Over Where RowNumber between

答案 1 :(得分:1)

使用子查询:

;with cte as(
             select ROW_NUMBER() OVER (ORDER BY AdsDate asc ) AS AdsIndex, 
                    AdsId, 
                    AdsEnTitle 
             from Advertisement
             where Status=N'True')
select * from cte
where AdsIndex<=17 and AdsIndex>=11

或者:

select * from (select ROW_NUMBER() OVER (ORDER BY AdsDate asc ) AS AdsIndex, 
                    AdsId, 
                    AdsEnTitle 
               from Advertisement
               where Status=N'True') as cte
where AdsIndex<=17 and AdsIndex>=11

答案 2 :(得分:1)

你不能在Where子句中获得 Rowno 。你必须 cte或子查询

with cte as
(
select ROW_NUMBER() 
OVER (ORDER BY Advertisement.AdsDate asc ) AS AdsIndex 
,Advertisement.AdsId , Advertisement.AdsEnTitle from Advertisement
where Advertisement.Status=N'True' 
)

select * from cte where  AdsIndex between 11 and 17