Row_Number () in SQLServer

select 
   sp_una_stl_key, 
   row_number() over(order by sp_una_stl_key)as stl_key 
from        
    t_unit_data_archive
where 
    stl_key>=10

This request is not executed, throws,

Msg 207, Level 16, State 1, Line 2 Invalid column name 'stl_key'.

I could not understand what the problem was. please help me!

+3
source share
3 answers

You cannot directly use ROW_NUMBER - you need to package it inside the Common Table expression as follows:

with CTE as
(
  select 
     sp_una_stl_key, row_number() over(order by sp_una_stl_key) as stl_key 
  from 
     t_unit_data_archive
)
select *
from CTE
where stl_key >= 10

Mark

+8
source

another way, although I would prefer CTE

select * from (select 
   sp_una_stl_key, 
   row_number() 
   over(order by sp_una_stl_key)as stl_key 
from        
    t_unit_data_archive) x
where 
    stl_key>=10
+1
source

where. :

select * from 
(select sp_una_stl_key, row_number() over(order by sp_una_stl_key)as stl_key 
from t_unit_data_archive) a
where stl_key>=10
+1

Source: https://habr.com/ru/post/1711081/


All Articles