mysql--实现oracle的row_number()over功能并组词两个字
有时候我们想要得到每个分组的前⼏条记录,这个时候oracle中row_number函数使⽤⾮常⽅便,但可惜mysql没有。⽹上搜了些实现⽅法。表flow_task有phaseno(序列号),objectno(编号)等⼏个字段,我们想实现根据编号字段分组,然后组内根据序列号排序功能
select@rownum:=@rownum+1 rownum,a.objectno,a.phaseno,
if(@objno=a.OBJECTNO or (@objno is null and a.objectno is null),
@rank:=@rank+1,
@rank:=1) as row_number,
@objno:=a.OBJECTNO
from(SELECT*from flow_task order by OBJECTNO,phaseno asc)a,
(select@rownum :=0,@objno:=null,@rank:=0)b
注意:order by OBJECTNO,phaseno asc 分组字段在前,排序字段在后
运⾏结果:
原理是,先 order by OBJECTNO,phaseno asc,这样后相同编号的记录会在⼀块⼉,并且已经是phaseno有序asc的
select的字段⼀个⼀个的看:
@rownum:=@rownum+1,每⼀⾏在上⾏@rownum变量值的基础上+1
if(@objno=a.OBJECTNO or (@objno is null and a.objectno is null),@rank:=@rank+1,@rank:=1),每⼀⾏判断,当前⾏的objectno(编号)是否等于上⼀个@objno变量值,如果是在上⼀个@rank变量值基础上+1,否则@rank赋值1
@objno:=a.OBJECTNO,当前⾏objectno赋值给变量@objno
ps:如果想要分组后某个字段的⼏个值,也可以使⽤group_concat函数
select a.objectno,group_concat(ifnull(a.phaseno,'')) phaseno
from(SELECT*from flow_task order by OBJECTNO,phaseno asc)a
GROUP BY a.objectno
电影源代码的主要内容运⾏结果:
可以看到,group_concat函数把分组后某个字段的值⽤,拼接起来
要获取前3个值,使⽤substring_index函数
select a.objectno,group_concat(ifnull(a.phaseno,'')) phaseno,substring_index(group_concat(ifnull(a.phaseno,'')),',',3) sub_phaseno
from(SELECT*from flow_task order by OBJECTNO,phaseno asc)aant design 删库
GROUP BY a.objectno
扩展下:怎样实现oracle中的rank() 和dense_rank()呢?我们知道rank()排序类似:1 2 ,dense_rank()排序类似:1 2
rank()实现:
select@rownum:=@rownum+1 rownum,a.objectno,a.phaseno,
if(@objno=a.OBJECTNO or (@objno is null and a.objectno is null),
if(@phaseno=a.phaseno or (@phaseno is null and a.phaseno is null),@rank,if(@sk=0,@rank:=@rank+2,@rank:=@rank+1)),
@rank:=1numa技术主要用于实现
)
as row_number,
if(@objno=a.OBJECTNO or (@objno is null and a.objectno is null),
if(@phaseno=a.phaseno or (@phaseno is null and a.phaseno is null),@sk:=0,if(@sk=0,@sk:=2,@sk:=1)),
@sk:=1
) as skip,
@objno:=a.OBJECTNO,
@phaseno:=a.phaseno
from(SELECT*from flow_task order by OBJECTNO,phaseno asc)a,
(select@rownum :=0,@objno:=null,@phaseno:=null,@rank:=1,@sk:=1)b
dense_rank()实现:
select@rownum:=@rownum+1 rownum,a.objectno,a.phaseno,
if(@objno=a.OBJECTNO or (@objno is null and a.objectno is null),rectify和modify的区别
if(@phaseno=a.phaseno or (@phaseno is null and a.phaseno is null),@rank,@rank:=@rank+1),
@rank:=1
) as row_number,
@objno:=a.OBJECTNO,
@phaseno:=a.phaseno
from(SELECT*from flow_task order by OBJECTNO,phaseno asc)a,
(select@rownum :=0,@objno:=null,@phaseno:=null,@rank:=1)b
>mysql语句转oracle
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论