来自Oracle DB表的第二高值

时间:2016-08-23 11:32:04

标签: sql oracle greatest-n-per-group

根据表格:

SELECT 
  * 
FROM  
  (SELECT 
    us.*,
    ROWNUM row_num
  FROM  
    (SELECT 
      u.*
    FROM
      users u
    ORDER BY
      u.BALANCE DESC) us
  WHERE
    ROWNUM < 3)
WHERE
  row_num > 1;

如何创建以最强效率方式返回第二高用户余额的查询?

我成功地使用查询来获取此记录(但不是通过有效的方式):

//...
import Dropzone from 'react-dropzone';

class SampleDropzone  extends React.Component{

    constructor(props, context) {
        console.log("Recruitment constructor");
        super(props, context);
        this.state = {
            dropzoneText: "Drop your files here..."
        };
    }

    wait(ms){
        var start = new Date().getTime();
        var end = start;
        while(end < start + ms) {
            end = new Date().getTime();
        }
    }

    onDrop(files) {

        files.forEach((file)=> {
            console.log('Received file: ', file.name);
            this.setState({dropzoneText: file.name});
            //this.saveFileToServerFromDropzone(file);
            this.wait(1000)
        });
    }

    render() {
    return(
        <div>
            <Dropzone onDrop={this.onDrop.bind(this)}>
            {this.state.dropzoneText}
            </Dropzone>
        </div>
    );
    }

};

3 个答案:

答案 0 :(得分:3)

我会使用窗口函数:

Intent myIntent = new Intent(MainActivity.this , NotifyService.class);     
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getService(ThisApp.this, 0, myIntent, 0);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, YOUR_HOUR);
cal.set(Calendar.MINUTE, 00);
cal.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 31556952000 , pendingIntent);  //set repeating every year

我认为您的查询会有很大的性能差异(特别是select * from ( select u.*, dense_rank() over (order by balance desc) as rnk from users u ) t where rnk = 2; 上没有索引),但在我看来,它更易于阅读和维护。

答案 1 :(得分:1)

试试这个:

SELECT * 
FROM (SELECT *   
      FROM USERS   
      ORDER BY balance DESC  
      FETCH FIRST 2 ROWS ONLY
      ) 
ORDER BY balance DESC  
FETCH FIRST 1 ROWS ONLY

答案 2 :(得分:0)

即使多个用户拥有相同的第二大余额,这也应该有效。

select * from USERS where balance IN
  (select max(balance) 
     from (select balance from USERS 
    where balance NOT IN (select max(balance) from USERS))
);