oracle sql(按某个字段分组然后从每组取出最大的一条纪录)?
比如表 mo_partprg
字段有:listid recid
1 1
1 2
2 3
2 4
2 5
想得到的数据是 按照 listid 分组 然后取出每组中recid最大的那几条纪录。结果应该是这两条纪录:
字段:listid recid
1 2
2 5
写法如下:
select listid,recid
from ( select listid,recid,row_number() over(partition by listid order by recid desc) rn
from mo_partprg)t1 where rn=1;
来自:http://mrliuliming.blog.sohu.com/131098537.html
积分商城需求:获取审核通过后的最后一条记录: 数据源:select bwip.busi_ware_id, bwip.busi_id, bwip.ware_code, bwip.ware_name,bwip.last_update_date,bwip.busi_state
from busi_ware_info_parent bwip
where bwip.ware_code = '951383'
order by bwip.last_update_date
要求: 需求获取红色部分的内容,,那么对应的SQL语句为 select ware_code, busi_ware_id
from ( select bwip.ware_code,
bwip.busi_ware_id,
row_number() over(partition by bwip.ware_code order by bwip.busi_ware_id desc) rn
from busi_ware_info_parent bwip,
ware_pc_rlt wpr,
busi_ware_info bwi
where bwip.type_code in ('5' , '6')
and bwip.ware_id = wpr.p_ware_id
and wpr.c_ware_id = bwi.ware_id
and bwip.ware_code = '951383'
)
where rn = 1
其中: row_number() over( partition by 分组字段 order by 排序字段 desc