Get the top row after order by in Oracle Subquery

前端 未结 4 1578
一整个雨季
一整个雨季 2021-02-15 17:19

I have a table student(id, name, department, age, score). I want to find the youngest student who has the highest(among the youngest students) score of each department. In SQL S

相关标签:
4条回答
  • 2021-02-15 18:00

    try this one

    select * from
      (SELECT id, name, department, age, score,
      ROW_NUMBER() OVER (partition by department order by age desc, score asc) srlno 
      FROM student) 
    where srlno = 1;
    
    0 讨论(0)
  • 2021-02-15 18:01

    In addition to Allan's answer, this works fine too:

    select * 
    from (SELECT * 
      FROM student
      order by age asc, 
               score desc) 
    where rownum = 1;
    
    0 讨论(0)
  • 2021-02-15 18:01

    In addition to Bharat's answer, it is possible to do this using ORDER BY in the sub-query in Oracle (as point out by Jeffrey Kemp):

    SELECT *
    FROM   student s1
    WHERE  s1.id IN (SELECT id
                     FROM   (SELECT   id, ROWNUM AS rn
                             FROM     student s2
                             WHERE    s1.department = s2.department
                             ORDER BY age ASC, score DESC)
                     WHERE  rn = 1);
    

    If you use this method, you may be tempted to remove the sub-query and just use rownum = 1. This would result in the incorrect result as the sort would be applied after the criteria (you'd get 1 row that was sorted, not one row from the sorted set).

    0 讨论(0)
  • 2021-02-15 18:19
    select to_char(job_trigger_time,'mm-dd-yyyy') ,job_status from
    (select * from kdyer.job_instances ji INNER JOIN kdyer.job_param_values pm 
    on((ji.job_id = pm.job_id) and (ji.job_spec_id = '10003') and (pm.param_value='21692') )
    order by ji.job_trigger_time desc)
    where rownum<'2'
    
    0 讨论(0)
提交回复
热议问题