繁体   English   中英

为什么 Row_number function 在使用 Where = 2 时会产生错误

[英]Why is the Row_number function is generatign an error when using Where = 2

我正在使用 Row_Number 和 order by function 对数据集进行排序。 我想知道 N = 2 的值。查询运行良好,我不使用“where N = 2”。 但是当我添加 'where N =2' 时,我得到了错误。 我该如何解决这个问题?

消息 207 级别 16 State 1 第 15 行无效的列名称“N”

下面的代码示例

create table temp 
(
    col1 nvarchar(25), 
    col2 nvarchar(25)
)

insert into  temp
values ('Babahoyo', 'Ecuador'),
       ('Stavanger', 'Norway'),
       ('Seattle', 'USA'),
       ('New York City', 'USA')

select 
    row_number() over (order by col2) as N, 
    col1, col2
from
    temp
where 
    N = 2

数据库小提琴

您不能在where clause中放置an alias reference

select * from
(
select row_number() OVER (ORDER BY col2) as N, col1, col2
from temp
)A
where n = 2

使用offset / fetch

select t.*
from temp
order by col2
offset 1 row fetch 1 row only

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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