在group by 语句中使用max()函数求它最大值,我还要取出对应于最大值的那一条数据的其它某一字段,如何实现?谢谢了.

解决方案 »

  1.   

    如果max()取出的最大值是唯一的,可以通过该最大值进行联接查询出任何你想要的字段如果不唯一,可以使用分析函数
      

  2.   

    谢谢,我对其中具体实现还是不太明白,如果是以下
    create  table temp_2
    (
       drill_id varchar2(20) primary key,
       dept_id varchar2(30),
       footage number(6,2)
     
    );
    insert into temp_2(drill_id,dept_id,footage) values('1','a','1000');
    insert into temp_2(drill_id,dept_id,footage) values('2','a','2000');
    insert into temp_2(drill_id,dept_id,footage) values('3','a','2000');
    insert into temp_2(drill_id,dept_id,footage) values('4','b','1000');commit;如果要查询以下以下情况
    select max(footage),
    --第二个查询字段为最大的值对应的drill_id
     from temp_2 group by dept_id;
     该如何实现了
      

  3.   

    QL> select * from temp_2
      2  WHERE footage=(SELECT MAX(footage) FROM temp_2);DRILL_ID             DEPT_ID                         FOOTAGE
    -------------------- ------------------------------ --------
    2                    a                               2000.00
    3                    a                               2000.00
      

  4.   

    可以使用分析函数
    SQL> select * from temp_2;
     
    DRILL_ID             DEPT_ID                         FOOTAGE
    -------------------- ------------------------------ --------
    1                    a                               1000.00
    2                    a                               2000.00
    3                    a                               2000.00
    4                    b                               1000.00
     
    SQL> 
    SQL> select drill_id,dept_id,footage
      2  from
      3  (
      4  select a.*,rank() over(partition by dept_id order by footage desc) rn
      5  from   temp_2 a
      6  )
      7  where  rn=1
      8  ;
     
    DRILL_ID             DEPT_ID                         FOOTAGE
    -------------------- ------------------------------ --------
    2                    a                               2000.00
    3                    a                               2000.00
    4                    b                               1000.00根据DEPT_ID分组,对于a,FOOTAGE最大值有2个
      

  5.   

    select drill_id,dept_id,footage
     from
      (
      select a.*,row_number() over(partition by dept_id order by footage desc) rn
     from   temp_2 a
     )
     where  rn=1