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