表 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这个语句怎么写好? 求助各位!!!
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这个语句怎么写好? 求助各位!!!
select distinct BUSI_SID,max(LOGTYPE),max(SUBTYPE),max(CURSTATUSTYPE) from 表 group by busi_sid
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的数据
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;
这种查询出的结果不会把busi_sid 过滤掉哦。
select * from T where not exists(select 1 from T a where busi_sid=a.busi_sid and CURSTATUSTYPE>a.CURSTATUSTYPE)
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
以上是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);
分析函数需要数据库版本的支持,如果没有支持就只能用group by来做了。
SELECT * FROM tt
WHERE CURSTATUSTYPE IN (
SELECT MAX(CURSTATUSTYPE) FROM tt
group by BUSI_SID)
group by BUSI_SID,LOGTYPE,SUBTYP,CURSTATUSTYPE
where not exists(select 1 from t b
where a.busi_id=b.busi_id and a.CURSTATUSTYPE<b.CURSTATUSTYPE)