mysql中类似oracle的over() row_number()的功能实现
从网上找了很多资料,参考了如下链接,完成了一个需求:下一行的开始时间,作为上一行开始时间的结束时间。
https://www.cnblogs.com/yhzh/p/6222580.html
以下是自己做的,可以忽略
-- 说明如下:
-- 先按照设备号,用户id,book_id,阅读时间 排序
-- 然后按照设备号分组,对组内的数据按时间 依次编号
-- 首先last_device_num 为空,
-- 第一行判断 device_num = null,所以赋值1,并把第一行的device_num 传递给last_device_num;
-- 第二行时,判断device_num是否等于上一行的device_num(即last_device_num),如果等,则递增,否则为1。
-- 第二行,纯粹是用来赋值。
UPDATE
xxx p,
(SELECT
n.id,
n.begin_time,
m.begin_time AS end_time,
TIMESTAMPDIFF(
SECOND,
n.begin_time,
m.begin_time
) AS interva
FROM
(SELECT
id,
device_num,
begin_time,
IF(
@last_device_num = a.device_num,
@rank := @rank + 1,
@rank := 1
) AS row_number,
@last_device_num := a.device_num
FROM
(SELECT
*
FROM
xxx
ORDER BY device_num,
user_id,
book_id,
begin_time ASC) a,
(SELECT
@rownum := 0,
@last_device_num := NULL,
@rank := 0) b) m
RIGHT JOIN
(SELECT
id,
device_num,
begin_time,
IF(
@last_device_num1 = a.device_num,
@rank1 := @rank1 + 1,
@rank1 := 2
) AS row_number,
@last_device_num1 := a.device_num
FROM
(SELECT
*
FROM
xxx
ORDER BY device_num,
user_id,
book_id,
begin_time ASC) a,
(SELECT
@rownum1 := 0,
@last_device_num1 := NULL,
@rank1 := 1) b) n
ON m.row_number = n.row_number
AND m.device_num = n.device_num) q
SET
p.`end_time` = q.end_time,
p.`read_time` = q.interva
WHERE p.id = q.id