简体   繁体   中英

Why i get error in sql server ROW_NUMBER()?

I'm new to SQL Server and write this query:

SELECT  ROW_NUMBER() over (ORDER BY TelNo ) as RowNum,
        Telno  
FROM [ClubEatc].[dbo].[GetOnlineBills]
where RowNum=1

When I run that query, I get this error:

Msg 207, Level 16, State 1, Line 11

Invalid column name 'RowNum'.

How can i solve that?

thanks all.

Try it this way,

SELECT *
FROM ( SELECT ROW_NUMBER() over (ORDER BY TelNo ) as RowNum, Telno  
        FROM [ClubEatc].[dbo].[GetOnlineBills]
     ) AS tbl
WHERE RowNum=1

You can't filter a ranking function result in the same select statement. Use the below script.

with cte_1
as
(
SELECT ROW_NUMBER() over (ORDER BY TelNo ) as RowNum,Telno  FROM [ClubEatc].[dbo].[GetOnlineBills])
SELECT *
FROM cte_1
where RowNum=1

You get this error because you cannot use computed column allias in WHERE statement, or even put where ROW_NUMBER() over (ORDER BY TelNo ) = 1 because it is forbidden.

You dint need to use CTE or sub-query's, just use TOP 1 WITH TIES with ordering by ROW_NUMBER() :

SELECT TOP 1 WITH TIES Telno  
FROM [ClubEatc].[dbo].[GetOnlineBills]
ORDER BY ROW_NUMBER() over (ORDER BY TelNo) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM