无法在 where 子句中使用的排名别名

Alias to rank not able to use in where clause

create table tab1(sno int, name varchar(30), age int);

insert into tab1 values(1, 'abc1', 22);
insert into tab1 values(2, 'abc2', 23);
insert into tab1 values(3, 'xyz', 28);
insert into tab1 values(4, 'abc3', 26);
insert into tab1 values(5, 'abc4', 25);

select sno, name, age, rank() over (order by sno) as ranking from tab1 where
ranking = trunc((select count(*)/2 from tab1)) + 1; //This query is giving error

错误是 ORA-00904:"RANKING":标识符无效

你的问题是感谢你在 select 中定义了一个别名,然后你想按它来过滤。您需要使用 CTE 或子查询:

with cte as (
      select sno, name, age, rank() over (order by sno) as ranking
      from tab1
     )
select cte.*
from cte
where cte.ranking = trunc((select count(*)/2 from tab1)) + 1; 

您似乎想计算中值。我绝对不会为此目的推荐 rank(),因为它处理平局的方式。更好的选择是 row_number(),所以这非常接近中位数。而且,您不需要子查询:

with cte as (
      select sno, name, age, row_number() over (order by sno) as ranking,
             count(*) over () as cnt
      from tab1
     )
select cte.*
from cte
where 2*cte.ranking in (cnt, cnt + 1)

这对偶数行和奇数行都适用。

您可能还对 MEDIAN()PERCENTILE_DISC()PERCENTILE_CONT() 函数感兴趣。

您正在尝试根据完成所有过滤后计算出的值来过滤 select 的结果。你需要把它改成这样:

select * from (
  select sno, name, age, rank() over (order by sno) as ranking from tab1 
) where ranking = trunc((select count(*)/2 from tab1)) + 1;