表 T 数据如下:BUSI_SID  LOGTYPE SUBTYPE CURSTATUSTYPE 
xt001  2 201 2     
xt002  2 201 5     
xt001  2 201 8     
查询时 如果 busi_sid 相同的只取 CURSTATUSTYPE最大的记录。想得到结果:
 
BUSI_SID  LOGTYPE SUBTYPE CURSTATUSTYPE      
xt002  2 201 5     
xt001  2 201 8这个语句怎么写好? 求助各位!!! 

解决方案 »

  1.   


    select distinct BUSI_SID,max(LOGTYPE),max(SUBTYPE),max(CURSTATUSTYPE) from 表 group by busi_sid
      

  2.   

    select * from t, (
      select busi_id, max(curstatustype) mt from t group by busi_sid) a
      where t.busi_id = a.busi_id and t.curstatustype = a.mt
    group by busi_sid, logtype, subtype, curstatustype  --去掉可能存在同样是最大的crustatustype的数据
      

  3.   


    select BUSI_SID, LOGTYPE, subtype, CURSTATUSTYPE from (
    select BUSI_SID, LOGTYPE, subtype, CURSTATUSTYPE, row_number() over(partition by BUSI_SID order by CURSTATUSTYPE desc) rn
    from t) tab where  rn = 1;
      

  4.   


    这种查询出的结果不会把busi_sid 过滤掉哦。
      

  5.   


    select * from T where not exists(select 1 from T  a where busi_sid=a.busi_sid and  CURSTATUSTYPE>a.CURSTATUSTYPE)
      

  6.   

    select BUSI_SID,LOGTYPE,SUBTYPE,CURSTATUSTYPE from (select BUSI_SID,LOGTYPE,SUBTYPE,CURSTATUSTYPE, row_number() over(partition by BUSI_SID order by CURSTATUSTYPE desc) index_no from T) where index_no = 1;
      

  7.   

    用分析函数
    select busi_sid,logtype,subtype,curstatustype
    from
    (select busi_sid,logtype,subtype,curstatustype,row_number() over(partition by busi_sid order by curstatustype desc) rn
    from t) where rn=1
      

  8.   


    以上是10g的写法,支持分析函数如果不支持的话select BUSI_SID,LOGTYPE,SUBTYPE,CURSTATUSTYPE from T where exists (select 1 from (select BUSI_SID, max(CURSTATUSTYPE) max_cnt from T group by BUSI_SID) b where b. BUSI_SID=T.BUSI_SID and  b.max_cnt=T.CURSTATUSTYPE and rownum = 1);
      

  9.   


    分析函数需要数据库版本的支持,如果没有支持就只能用group by来做了。
      

  10.   

    分析函数在8i,9i中也是可以用的(我已测试),并不是10g才可以的吧好像正则表达式是10g以后才支持的。
      

  11.   

    下面的SQL应该可以达到上述要求的效果:
    SELECT * FROM tt 
      WHERE CURSTATUSTYPE IN (
      SELECT MAX(CURSTATUSTYPE) FROM tt 
      group by BUSI_SID)
      group by BUSI_SID,LOGTYPE,SUBTYP,CURSTATUSTYPE
      

  12.   

      select * from t a
      where not exists(select 1 from t b
      where a.busi_id=b.busi_id and a.CURSTATUSTYPE<b.CURSTATUSTYPE)