【问题标题】:sql rank diplay requested rank numbersql rank 显示请求的rank数
【发布时间】:2018-09-24 22:25:54
【问题描述】:

查询:

SELECT distinct 
rank() OVER (ORDER BY p.service) as rank,
p.service, 
From table_service
Where 1=1

输出:
排名:1 |服务:test1
排名:2 |服务:test2
排名:3 |服务:test3

我如何才能只显示 Rank 2 ?

我试过了,但没有用:

SELECT distinct 
rank() OVER (ORDER BY p.service) as rank,
p.service, 
From table_service
Where rank = 2

有什么想法吗?

【问题讨论】:

    标签: sql rank


    【解决方案1】:

    你可以尝试使用子查询,因为where不能使用别名来做条件。

    SELECT * FROM (
        SELECT 
            rank() OVER (ORDER BY p.service) as rank,
            p.service, 
        From table_service
    ) t1
    where rank = 2
    

    【讨论】:

    • 你是个天才!
    【解决方案2】:

    将您的查询放入子查询中:

    select *
    from
    (
    SELECT distinct 
    rank() OVER (ORDER BY p.service) as rank,
    p.service, 
    From table_service
    ) sub
    Where rank = 2;
    

    【讨论】:

    • 你是个天才!
    【解决方案3】:

    为什么要使用排名?大多数数据库都支持offset/fetch 或类似的东西:

    select p.service,
    from table_service p
    order by p.service
    offset 1 fetch first 1 row only;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 2018-04-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多