从记录中选择具有最高值或第二高值的名称

时间:2018-02-21 15:55:18

标签: sql db2

我想从排名为' First'的表中选择名称。 如果没有记录,排名=' First'然后在排名为' Second'。

的地方取名

示例:

--------------------
ID F_NAME  RANKING
--------------------
1  Tom     Second
2  John    Third
3  Sarah   First
--------------------

预期产出:莎拉

ID F_NAME  RANKING
--------------------
1  Tom     Second
2  John    Third
3  James   Fourth
--------------------

预期输出:Tom

仅显示第一个或第二个。像Third,Fourth这样的其他人并不重要。

此查询适用于DB2。我怎么写这样的查询?

2 个答案:

答案 0 :(得分:0)

您可以使用ORDER BYFETCH FIRST

SELECT *
FROM table
WHERE Ranking IN ('First', 'Second')
ORDER BY Ranking
FETCH FIRST 1 ROW ONLY;

<强> DBFiddle Demo

答案 1 :(得分:0)

row_numberorder by中的条件表达式一起使用。

select *
from (select t.*,row_number() over(order by case when ranking='First' then 1
                                                 when ranking='Second' then 2
                                                --add more rankings as needed
                                            else 3 end) as rnum 
      from tbl t
     ) t
where rnum=1
相关问题