mysql实现rownum()over_mysql 实现row_number() over(partition by ) 分组排序功能

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 16:08   1708   0

创建表:

b68ca45e5773ee297e766f9f6c613a72.png

插入数据:

280c69800ba7630921313a86c0e09e5d.png

生成行号:

f798f2db77d5dab8a3eb8100d60ccc43.png

生成row_number效果1:

aa8aa036e1eaa23bfeeba1f735a6f6dd.png

生成row_number效果2:

1f9ae7f478bd057a8659424bdb1f11a5.png

注意点:“

SELECT IF(@UID = T.ID AND @CID = T.PID,

@RANK := @RANK + 1,

@RANK := 1) AS RANK2,

”需要命名别名

附:代码

DESC USERS;

SELECT * FROM USERS;

-- 给USERS里的数据设置行号, RN是行号

SELECT @ROWNUM := @ROWNUM + 1 AS RN, T.

FROM (SELECT @ROWNUM := 0) R, USERS T

SELECT IF(@UID = T.ID AND @CID = T.PID,

@RANK := @RANK + 1,

@RANK := 1) AS RANK2,

T.,

@UID := T.ID,

@CID := T.PID

FROM (SELECT @UID := NULL, @CID := NULL, @RANK := 0) R,

(SELECT PID, NAME, ID

FROM USERS

ORDER BY PID, NAME, ID) T;

SELECT IF(@UID = T.PID,

@RANK := @RANK + 1,

@RANK := 1) AS RANK2,

T.*,

@UID := T.ID,

@CID := T.PID

FROM (SELECT @UID := NULL, @CID := NULL, @RANK := 0) R,

(SELECT PID, NAME, ID

FROM USERS

ORDER BY PID, NAME, ID) T;

可以参考的其他类似处理方式:

select *,@rank:=case when @current_id<>pid then 1 else @rank+1 end as rank2,

@current_id:=id from users order by pid,name desc;

这段不是,记录:

SELECT

ID,SUBSTRING_INDEX(GROUP_CONCAT(PID ORDER BY NAME DESC),',',1) PID

FROM

(

SELECT

ID,PID,NAME

FROM

USERS

ORDER BY PID ASC ,NAME DESC

)B

GROUP BY ID

;

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP