1. 程式人生 > >oracle 分組排序取出最大和最小的記錄

oracle 分組排序取出最大和最小的記錄

表中欄位:phonenumber,score,examtime
要取出時間段中phonenumber的score最大並且examtime最小的記錄,用max和min取的值都不是正確的記錄值,用排序子查詢的方法可以取到

select phonenumber,score,examtime,scoretime,createtime,rn from (
SELECT phonenumber,score,examtime,scoretime,createtime,ROW_NUMBER() OVER(PARTITION BY phonenumber ORDER BY score DESC
,examtime) RN FROM t_db_scores WHERE to_date(scoretime,'yyyy-mm-dd hh24:mi:ss')>=to_date('2018-07-10 00:00:00','yyyy-mm-dd hh24:mi:ss') and to_date(scoretime,'yyyy-mm-dd hh24:mi:ss')<=to_date('2018-07-20 23:59:59','yyyy-mm-dd hh24:mi:ss') ) where rn=1

先按score降序、examtime升序對phonenumber分組排序,再只取rn=1的記錄,就可得到正確的結果

這裡寫圖片描述