表1sbh       lr         date
111       200         2009-01-01
111       300         2008-03-01
111       222         2009-02-01
222       333         2007-03-02
222       322         2007-09-02
333       523         2008-03-03 现在需要统计每个sbh中最后一次LR额sbh       lr         date
111       222        2009-02-01
222       322        2007-09-02
333       523        2008-03-03表1的数据是用另个select查询生成的,我用以下语句查出来结果是错的,结果显示了所有记录select sbh,lr,max(date) from 表1   group by sbh,lr
                
盼回复!!!

解决方案 »

  1.   

    select a1.sbh , (select 表1.lr from 表1 where 表1.sbh=a1.sbh and 表1.date=a1.date and rownum<2) as lr, a1.date
    from(
         select sbh,max(date) from 表1  group by sbh
    )a1
      

  2.   


    select *
    from 表1 a
    where not exists (select sbh from 表1 where sbh=a.sbh and date>a.date);
      

  3.   

    SELECT sbh,lr,DATE  
    FROM (
    SELECT 表1.* ,MAX(DATE ) over(PARTITION BY sbh) max_date FROM 表1 
    )
    WHERE DATE  = max_date
      

  4.   

    create table tb_1(sbh int,lr int,dated date);
    insert into tb_1 values(111,200,to_date('2009-1-1','yyyy-mm-dd'));
    insert into tb_1 values(111,200,to_date('2008-3-1','yyyy-mm-dd'));
    insert into tb_1 values(111,222,to_date('2009-2-1','yyyy-mm-dd'));
    insert into tb_1 values(222,333,to_date('2007-3-2','yyyy-mm-dd'));
    insert into tb_1 values(222,322,to_date('2007-9-2','yyyy-mm-dd'));
    insert into tb_1 values(333,523,to_date('2008-3-3','yyyy-mm-dd'));
    commit;
    select * from tb_1 t;select t1.*
      from tb_1 t1, (select max(t.dated) date2 from tb_1 t group by t.sbh) t2
     where t1.dated = t2.date2