Roc*_*cco 6 sql oracle oracle12c
我想弄清楚如何从5个字段获得2个最高值.我知道这个greatest功能,但我也不知道如何取出第二个最高值.
基本上,该表有5个NUMBER类型字段.在此示例中,最后两列是我想要的结果.
| Score1 | Score2 | Score3 | Score4 | Score5 | | Highest1_value | Highest2_value
+--------+--------+--------+--------+--------+ +----------------+---------------
| 10 | 20 | 30 | 40 | 50 | | 50 | 40
| 20 | 20 | 12 | 17 | 0 | | 20 | 20
| 7 | 7 | 7 | 7 | 11.1 | | 11.1 | 7
| 10 | 10 | 10 | 10 | 10 | | 10 | 10
Run Code Online (Sandbox Code Playgroud)
对数据进行逆透视并用于row_number获取每个 id 的前 2 个最高分数。
select id
,max(case when rnum=1 then val end) as highest_1
,max(case when rnum=2 then val end) as highest_2
from (select id,score,val,row_number() over(partition by id order by val desc) as rnum
from (select * from t --replace this with your tablename
unpivot (val for score in (score1,score2,score3,score4,score5)) p
) tbl
) tbl
group by id
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
104 次 |
| 最近记录: |